Javascript 中的 addEventListener 自动触发点击事件

IT技术 javascript javascript-events
2021-03-03 14:43:19

我想做一个简单的javascript倒计时程序。由于某种原因,倒计时触发而我不必单击开始链接。

<!DOCTYPE HTML>
<html>
    <head>
        <title id = "titleElement">My Top Ten Movies</title>

    </head>

    <body>

        <p>Countdown Suren's favorite ten movies
            <a href="" id = "start"> Start </a>
        </p>

        <table>

            <thead>
                <tr>
                    <td>Number</td>
                    <td>Movie</td>
                </tr>   
            </thead>

            <tbody id = "movieList">

            </tbody>

        </table>

    <script src="js/practice.js"></script>  
    </body>
</html>

和我的 JavaScript 文件...

//get the start element
var start = document.getElementById("start");

//register listener
start.addEventListener('click', startCountDown(), false);


function startCountDown()
{
    //alert("Here!");
    //creat the list of 10 movies
    var myTenMovies = ["Breaveheart", "Mars Attacks", "Startship Troopers", "Jurassic Park", "Terminator 2",
                        "Austion Powers: Gold Member", "Fifth Element", "Bram Stocker's Dracula",
                        "Shashank Redemption", "LOTR: Return Of The King"];

    //get the location in the DOM to add each movie
    var tableLocation = document.getElementById("movieList");

    //create a timer function
    var countdown = setInterval(insertNextMovie, 750);

    //keep track of the index
    var index = 0;
    var movieRankIndex = 10;
    //alert("1");


    //function to add to DOM
    function insertNextMovie()
    {
        //alert("Here3!");
        //create a text nodes
        var movie = document.createTextNode(myTenMovies[index]);
        var rank = document.createTextNode(movieRankIndex);

        //create <td> element
        var rankData = document.createElement("td");
        var movieTitle = document.createElement("td");
        var row = document.createElement("tr");

        //add text to td
        rankData.appendChild(rank);
        movieTitle.appendChild(movie);

        //fill the row with data
        row.appendChild(rankData);
        row.appendChild(movieTitle);

        if(movieRankIndex == 1)
        {
            row.setAttribute("bgcolor", "yellow");
            //row.setAttribute("align", "right");
        }
        //add td to DOM table
        tableLocation.appendChild(row);

        //append index
        index++;
        movieRankIndex--;

        if(index == 10)
        {
            clearInterval(countdown);
        }

    }

    //alert("2");
}
1个回答

那是因为startCountDown()调用了函数startCountDown删除括号,它会起作用。

我删除了括号,它不再自动运行,但现在我点击开始后什么也不做。
2021-04-21 14:43:19
@Suren:您可以接受答案(单击复选框使其变为绿色)
2021-04-23 14:43:19
美丽的!!1 为你高级 Zirak!
2021-04-30 14:43:19
这可能是中断执行的锚点。删除该href属性或将其更改为#
2021-05-17 14:43:19