JavaScript代码中的onclick事件处理程序,而不是html标签 [英] onclick event handler in javascript code, not html tag

查看:133
本文介绍了JavaScript代码中的onclick事件处理程序,而不是html标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图确保我的网页使用的是不引人注目的JavaScript时,我似乎无法使onclick事件在我的javascript中起作用,但它仅作为html标签中的事件起作用.这是代码

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. 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.

很有可能在DOM完成加载之前附加了事件功能代码.

Most likely, the event function code is being attached before the DOM has finished loading.

或者,您可能使用的浏览器不支持onclick(尽管这不太可能!).为了确保它可以正常工作,您可以将后备广告用于附加事件的主要途径:

Alternatively, you might be using a browser which doesn't support onclick (though this is unlikely!). 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; 
}

这篇关于JavaScript代码中的onclick事件处理程序,而不是html标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆