将 onclick 事件添加到 div

add an onclick event to a div(将 onclick 事件添加到 div)

本文介绍了将 onclick 事件添加到 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't know if this is allowed or even possible. Is it possible to create a div element with an onclick event so that if anywhere in the div's area is clicked, the event will run.

例如JAVASCRIPT:

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

生成的 HTML:

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

 whatever content I decide to add to the divTag.innerHTML

<小时>

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


I notice how theres no onclick command going through to the generated div. Id this because its not allowed?

那么 2 个问题.

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

1:Is it possible to add onclick to a div and have it occur if any area of the div is clicked. 2:If yes then why is the onclick method not going through to my div.

多么奇怪:

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

以上功能完美无缺.

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

All below don't and wont pass the onclick to the div.

divTag.onclick=printWorking;

divTag.onclick="printWorking";

divTag.onclick="printWorking()";

还尝试了多种其他变体.

Multiple other variants have been tried too.

推荐答案

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

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

是的……尽管应该谨慎行事.确保有某种机制允许键盘访问.建立在有效的基础上

Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

如果是,那么为什么 onclick 方法没有通过我的 div.

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

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

You are assigning a string where a function is expected.

divTag.onclick = printWorking;

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

There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

也就是说,现在是 2019 年,旧版本的 Internet Explorer 在实践中不再存在,因此您可以直接访问 addEventListener

That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener

这篇关于将 onclick 事件添加到 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将 onclick 事件添加到 div