最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript onclick event triggering on page load - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 6

Remove the parenthesis from the function name (doing so invokes it):

document.getElementById("clickMe").onclick = bar;

jsFiddle example

发布评论

评论列表(0)

  1. 暂无评论