无法基于按钮元素“ id”调用JavaScript方法

问题描述 投票:0回答:1

我正在遵循Head First Javascript的教程。在本教程中,showBlogs()方法通过以下html代码调用

HTML按钮<input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />

function showBlogs(numberOfEntries){

        //sort the blogs in reverse chronological order (most recent first)
        blogs.sort(function(blog1, blog2){
            return blog2.date - blog1.date;
        })

        //set the number of entires if non specified
        if(!numberOfEntries){
            numberOfEntries = blogs.length;
        }

        //set blog entries
        var currenetBlog = 0; blogListHTML = "";
        while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
            blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0); 
            currenetBlog++;
        }

        //display blog entries
        blogsDOM.innerHTML = blogListHTML;

    }

但是,当我创建另一个按钮并通过javascript访问它并使用事件处理程序调用相同的方法时-没有任何反应。

按钮<button type="button" id="showAllBlogs">Show All Posts</button>

JavaScript中的访问按钮const showBlogsButton = document.getElementById('showAllBlogs');

调用showBlogs方法showBlogsButton.addEventListener('click', showBlogs);

[我确实尝试创建另一个函数'foo()',然后使用新按钮调用了foo(),并且能够调用该方法。但是,当我调用showBlogs()方法时,什么也没发生。

JAVASCRIPT CODE



`
//dom elements
    const blogsDOM = document.getElementById('blog');
    const query = document.getElementById('searchInput');
    const searchButton = document.getElementById('searchButton');
    const showBlogsButton = document.getElementById('showAllBlogs');


    // Constructor
    function Blog(body, dateString){
        this.body = body;
        this.date = new Date(dateString);

        this.toString = function(){
            return this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' + 
                   this.body;
        };

        this.toHTML = function(highlight){
            var htmlPost = "";

            //determine to highlight post
            htmlPost += highlight ? "<p style='background-color: #EEEEEE'>" : "<p>";

            //generate formatted html
            htmlPost += this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' + 
            this.body + "</p>";

            //return html
            return htmlPost;
        };

        this.containsText = function(text){
            return this.body.toLowerCase().indexOf(text.toLowerCase()) > -1;
        };

    }

    //Array of blogs
    var blogs = [
        new Blog("Got the new cube I ordered", "01/25/1986"),
        new Blog("This new cube works just fine", "02/22/2000"),
        new Blog("This is going to be the third one", "03/23/2005"),
        new Blog("This is the final one", "03/21/2020")
    ]

    blogs.sort(function(blog1, blog2){ return blog2.date - blog1.date; })

    function getDaysBetweenDates(date1, date2){
        var daysBetween = (date2 - date1) / (1000 * 60 * 60 * 24);
        return Math.round(daysBetween);
    }

    function formatDate(date){
        return date.getDay() + '/' +  date.getMonth() + '/' + date.getYear();
    }

    function searchForPost(event){        
        let matchingBlogs = [];
        event.preventDefault();
        const searchQuery = query.value;

        blogs.forEach(blog =>{
            if(blog.body.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1){
                matchingBlogs.push(blog);
            }
        } )

        showBlogs(matchingBlogs.length, matchingBlogs);
    }

    //show list of blog
    function showBlogs(numberOfEntries, blogsToShow = blogs){

        //sort the blogs in reverse chronological order (most recent first)
        blogs.sort(function(blog1, blog2){
            return blog2.date - blog1.date;
        })

        //set the number of entires if non specified
        if(!numberOfEntries){
            numberOfEntries = blogs.length;
        }

        //set blog entries
        var currenetBlog = 0; blogListHTML = "";
        while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
            blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0); 
            currenetBlog++;
        }

        //display blog entries
        blogsDOM.innerHTML = blogListHTML;

    }

    searchButton.addEventListener('click', searchForPost);
    showBlogsButton.addEventListener('click', showBlogs);`

HTML CODE

`<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <h3>Youtube - the Blog for Cube puzzlers</h3>

    <div class="search-container">
        <input type="text" id="searchInput" placeholder="Search for a blog"/>
        <button type="button" id="searchButton">Search the blog</button>
    </div>
    <div id="blog"></div>
    <input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />
    <button type="button" id="showAllBlogs">Show All Posts</button>

    <script src="script.js"></script>

</body>
</html>`
javascript dom button event-handling
1个回答
0
投票

我在上面复制了您的代码,该函数已成功调用。

function showBlogs(numberOfEntries){
	console.log("Function Called");
}

const showBlogsButton = document.getElementById('showAllBlogs');
showBlogsButton.addEventListener('click', showBlogs);
<button type="button" id="showAllBlogs">Show All Posts</button>
© www.soinside.com 2019 - 2024. All rights reserved.