按钮上的Javascript“onclick”属性自动运行

时间:2015-12-22 18:18:38

标签: javascript html button onclick

我正在使用for循环来动态命名和填充按钮(带有文本和代码)。我遇到的一个问题是动态地为按钮分配onclick功能,但我似乎修复了它:

document.getElementById(ID_HERE).onclick = FUNCTION();

问题是当我添加此代码时,按钮会在网页加载时触发,而不是点击。

我在下面列出了HTML和Javascript的完整代码。

的JavaScript

var routes = "";
var elem = "";
var locationid = "50017"
var currentRoute = "the Londinium Way"
function possibleRoutes(){
    document.write("<div id='container'>");
    document.write("<center><b> Welcome to ");
    document.write(currentRoute);
    document.write("!<br>")
    document.write("Your options are:");
    for (i = 0; i<routes.length;i++){
        var options = routes[i];
        var temp = "button" + i
        document.write("<button id='button'></button>");
        document.getElementById('button').id = temp;
        document.getElementById(temp).innerHTML=routes[i][0];
        document.getElementById(temp).onclick = getRoutes(routes[i][1]);
        console.log(routes[i]);
        console.log(routes[i][1]);
    }
    document.write("<br><img src='http://192.168.1.151:8000/map.jpg'>");
    document.write("</b></center></div>");
}
function getRoutes(locationid) {
  var routesURL = 'http://cors.io/?u=http://orbis.stanford.edu/api/sites/' + locationid;
  $.ajax({
    type: 'GET',
    url: routesURL
  }).done(function(data) {
    console.dir(data);
    dataParsed = JSON.parse(data);
    currentRoute = dataParsed.prefname;
    routes = dataParsed.routes;
    console.log(routes);
    clearScreen();
  });
}
function clearScreen(){
    if (document.contains(document.getElementById("container"))){
            elem = document.getElementById("container");
            elem.remove();
    }
    possibleRoutes();
}

HTML

<html>
    <head>

        <title> Londinium Trail </title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script src="http://192.168.1.151:8000/scripts/game.js"> </script>
    </head>
    <body>
        <script>
        getRoutes(50017);
        </script>
    </body>
</html>

2 个答案:

答案 0 :(得分:3)

JAVASCRIPT

尝试改为使用addEventListener

document.getElementById(ID_HERE).addEventListener("click", myFunction);

JQUERY

如果你正在使用jquery:

$('body').on('click', '#ID_HERE', myFunction);

查看 addEventListener vs onclick

希望这有帮助。

答案 1 :(得分:2)

问题是您使用FUNCTION();

调用该函数

由于您的代码似乎使用的是JQuery,请考虑使用.on方法附加点击监听:

$(document).on('click', '#ID_HERE', function(){
  function_to_run();
});