向div添加onclick事件 [英] add an onclick event to a div

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

问题描述

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

divTag.onclick = printWorking;

虽然较旧版本的Internet Explorer有很大的不同,应该使用库来抽象它。有大量的非常小的事件库和每个主要库(例如 YUI 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 (such as YUI or jQuery) has event handling functionality.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆