Javascript";onclick";按钮上的属性自动运行
我使用for循环动态命名和填充按钮(使用文本和代码)。我遇到的一个问题是动态地将onclick功能分配给按钮,但我似乎已经用以下方法解决了这个问题:Javascript";onclick";按钮上的属性自动运行,javascript,html,button,onclick,Javascript,Html,Button,Onclick,我使用for循环动态命名和填充按钮(使用文本和代码)。我遇到的一个问题是动态地将onclick功能分配给按钮,但我似乎已经用以下方法解决了这个问题: document.getElementById(ID_HERE).onclick = FUNCTION(); 问题是,当我添加此代码时,按钮会在网页加载时自动触发,而不是单击 我在下面列出了HTML和Javascript的完整代码 JavaScript: var routes = ""; var elem = ""; var locationid
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>
<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>
var-routes=”“;
var elem=“”;
var locationid=“50017”
var currentRoute=“Londinium路”
函数possibleRoutes(){
文件。填写(“”);
文件。写信(“欢迎光临”);
文件写入(currentRoute);
文档。写(“!
”)
写下(“你的选项是:”);
对于(i=0;iJAVASCRIPT)
尝试改用addEventListener
:
document.getElementById(ID_HERE).addEventListener("click", myFunction);
JQUERY
如果您正在使用jquery:
$('body').on('click', '#ID_HERE', myFunction);
请看
希望这有帮助。JAVASCRIPT
尝试改用addEventListener
:
document.getElementById(ID_HERE).addEventListener("click", myFunction);
JQUERY
如果您正在使用jquery:
$('body').on('click', '#ID_HERE', myFunction);
请看
希望这能有所帮助。问题是您正在使用function()调用函数
<> p>因为您的代码似乎正在使用jQuery,请考虑使用.on方法附加单击侦听:
$(document).on('click', '#ID_HERE', function(){
function_to_run();
});
问题是您正在使用function()调用函数
<> p>因为您的代码似乎正在使用jQuery,请考虑使用.on方法附加单击侦听:
$(document).on('click', '#ID_HERE', function(){
function_to_run();
});