gpt4 book ai didi

javascript - 向 div 添加 onclick 事件

转载 作者:技术小花猫 更新时间:2023-10-29 11:50:48 26 4
gpt4 key购买 nike

我不知道这是否被允许甚至可能。是否可以创建一个带有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com