简体   繁体   English

JavaScript代码中的onclick事件处理程序,而不是html标签

[英]onclick event handler in javascript code, not html tag

when trying to ensure my webpage is using unobtrusive javascript I cant seem to get the onclick event to work in my javascript, it only works as an event in the html tag. 当试图确保我的网页使用的是不引人注目的javascript时,我似乎无法使onclick事件在我的javascript中起作用,它仅作为html标签中的事件起作用。 here is the code 这是代码

var dow = document.getElementById("dowDiv");
dow.onclick=function () {}

any reason that this isnt working for me? 有什么理由对我不起作用? as all the answers i can find say this is the way to do it, thanks in advance 因为我能找到的所有答案都说这是做到这一点的方法,在此先感谢

There could be several reasons based on the information provided. 根据提供的信息,可能有多种原因。

Most likely, the event function code is being attached before the DOM has finished loading. 最有可能在DOM完成加载之前附加了事件功能代码。

Alternatively, you might be using a browser which doesn't support onclick (though this is unlikely!). 另外,您可能使用的浏览器不支持onclick(尽管这不太可能!)。 To guarantee it will work, you can use fallbacks for the main routes of attaching an event: 为了确保它可以正常工作,您可以将后备广告用于附加事件的主要途径:

if (dow.addEventListener) {
  dow.addEventListener('click', thefunction, false);
} else if (dow.attachEvent) {
  dow.attachEvent('onclick', thefunction);
} else {
  dow.onclick = thefunction; 
}

Make sure that you only have one element with the id dowDiv . 确保您只有一个ID为dowDiv元素。 If you have z-index's on elements and something is over the div it might be blocking the click event on the div. 如果您的元素上具有z-index的元素,并且div上有内容,则可能会阻止div上的click事件。

 var dow = document.getElementById("dowDiv"); var out = document.getElementById("out"); var clickCount = 0; dow.onclick = function() { clickCount += 1; out.innerHTML = clickCount } 
 <div id="dowDiv">Hello onclick <span id="out"></span>!</div> 

You can use jQuery to achieve a simple o'clock function. 您可以使用jQuery实现简单的时钟功能。

Make you include jQuery BEFORE you reference your .js file: 在引用.js文件之前,请先包含jQuery:

<script src="path/to/jQuery.js"></script>
<script src="file.js></script>

With jQuery you can say 使用jQuery,您可以说

$('#dowDIV').click(function(){
   Do stuff here;
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM