将一个onclick事件添加到div

OVE*_*ONE 28 html javascript css onclick

我不知道这是允许的,甚至是不可能的.是否可以使用onclick事件创建div元素,以便在单击div区域中的任何位置时,将运行该事件.

例如JAVASCRIPT:

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.
Run Code Online (Sandbox Code Playgroud)

生成的HTML:

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

 whatever content I decide to add to the divTag.innerHTML
Run Code Online (Sandbox Code Playgroud)

我注意到如何没有onclick命令进入生成的div.这是因为它不允许吗?

那么2个问题呢.

1:是否可以向div添加onclick并在单击div的任何区域时发生.2:如果是,那么为什么onclick方法不会进入我的div.


多奇怪啊:

divTag.setAttribute("onclick", "printWorking()");
Run Code Online (Sandbox Code Playgroud)

以上工作完美无瑕.

以下所有都不会,并且不会将onclick传递给div.

divTag.onclick=printWorking;

divTag.onclick="printWorking";

divTag.onclick="printWorking()";
Run Code Online (Sandbox Code Playgroud)

还尝试了多种其他变体.

Que*_*tin 23

是否可以向div添加onclick并在单击div的任何区域时发生.

是的......虽然应该谨慎行事.确保有一些允许键盘访问的机制.建立有效的东西

如果是,那么为什么onclick方法不会进入我的div.

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

divTag.onclick = printWorking;
Run Code Online (Sandbox Code Playgroud)

虽然旧版本的Internet Explorer有很大的不同,您应该使用库来抽象它,但有更好的方法来分配事件处理程序.有很多非常小的事件库,每个主要的库(如YUIjQuery)都有事件处理功能.

  • 如果有括号,则它将是函数**call**,并且将返回返回值而不是函数本身. (3认同)