I have the following html/javascript:
<div id="clickMe" style="width:200px;height:100px;background-color:red;">
click me
</div>
<script>
function bar(){
alert("foo");
}
document.getElementById("clickMe").onclick = bar();
</script>
When I load this page, the function triggers and the alert pops up, and then it doesn't trigger when I click clickMe
. I tried switching the div
out for a button
and that worked fine (didn't trigger on page load, did trigger on click). When I ment out document.getElementById("clickMe").onclick = bar();
, the function doesn't trigger at all. I also tried adding onload
functions surrounding the whole thing, and just the function, and just the trigger, to no great effect.
How do I trigger a javascript function by clicking on a div, and why is this not working?
Thank you.
I have the following html/javascript:
<div id="clickMe" style="width:200px;height:100px;background-color:red;">
click me
</div>
<script>
function bar(){
alert("foo");
}
document.getElementById("clickMe").onclick = bar();
</script>
When I load this page, the function triggers and the alert pops up, and then it doesn't trigger when I click clickMe
. I tried switching the div
out for a button
and that worked fine (didn't trigger on page load, did trigger on click). When I ment out document.getElementById("clickMe").onclick = bar();
, the function doesn't trigger at all. I also tried adding onload
functions surrounding the whole thing, and just the function, and just the trigger, to no great effect.
How do I trigger a javascript function by clicking on a div, and why is this not working?
Thank you.
Share Improve this question asked Dec 2, 2013 at 3:26 James G.James G. 2,9044 gold badges29 silver badges55 bronze badges1 Answer
Reset to default 6Remove the parenthesis from the function name (doing so invokes it):
document.getElementById("clickMe").onclick = bar;
jsFiddle example
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745144667a4613592.html
评论列表(0条)