javascript - 向 div 添加 onclick 事件

标签 javascript css html onclick

我不知道这是否被允许甚至可能。是否可以创建一个带有 onclick 事件的 div 元素,以便如果单击 div 区域中的任何位置,该事件将运行。

例如 脚本:

var divTag = document.createElement("div");
divTag.id="new-ID"; 
var onClickCommand = "printWorking()"   //printworking is another method that simply print "I'm working" to the console
divTag.onclick = onClickCommand;
console.log("onclick command added");
console.log(divTag.onclick);
parentDiv.appendChild(divTag); //This simply adds the div tag to the page.

生成的 HTML:

 <!--<div id="new-ID">-->

 whatever content I decide to add to the divTag.innerHTML

我注意到生成的 div 中没有 onclick 命令。这是因为不允许吗?

那么有 2 个问题。

1:是否可以将onclick 添加到div 并在单击div 的任何区域时触发。 2:如果是那么为什么onclick方法没有通过我的div。


多么奇怪:

divTag.setAttribute("onclick", "printWorking()");

以上工作完美无缺。

以下所有内容都不会也不会将 onclick 传递给 div。

divTag.onclick=printWorking;

divTag.onclick="printWorking";

divTag.onclick="printWorking()";

也尝试了多种其他变体。

最佳答案

Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

是的……尽管应该谨慎行事。确保有某种机制允许键盘访问。 Build on things that work

If yes then why is the onclick method not going through to my div.

您正在分配一个需要函数的字符串。

divTag.onclick = printWorking;

虽然旧版本的 Internet Explorer 有很大的不同,但您应该使用一个库来抽象它,但有更好的方法来分配事件处理程序。有很多 very small event libraries和每个主要图书馆jQuery ) 具有事件处理功能。

也就是说,现在是 2019 年,旧版本的 Internet Explorer 实际上不再存在,因此您可以直接转到 addEventListener

关于javascript - 向 div 添加 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6909988/

相关文章:

javascript - 使用 JQuery is() 改变背景图像

javascript - 谷歌翻译默认语言

javascript - 数据表: Adding callback function on filter and get filtered data array

javascript - ||运算符在 null 时不设置默认值

html - Flexslider 将鼠标悬停在指示器上时,会显示其中的图像

javascript - 如何在不移动html中周围元素的情况下扩展图像?

javascript - Jquery 对话框不显示

javascript - Angular 无法识别提供程序内部的函数

php - wordpress 网站上的缩略图问题?

javascript - CSS:如何防止网格中出现空单元格(通过删除部分空行)