我不知道这是否被允许或者是否可行。是否可以创建一个带有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 命令。这是因为不允许吗?
那么有两个问题。
1:是否可以给 div 添加 onclick,并在单击 div 的任何区域时触发它? 2:如果可以,为什么我的 onclick 方法没有传递到 div 上。
非常奇怪:
divTag.setAttribute("onclick", "printWorking()");
上面的代码可以完美地运行。
以下所有代码都不能把 onclick 事件传递给 div 元素。
divTag.onclick=printWorking;
divTag.onclick="printWorking";
divTag.onclick="printWorking()";
还尝试了其他多种变体。