jQuery,单击时选择(任何所有 *)元素
我正在为自己构建一个调试工具。我想要它做的是,每当单击任何元素时,都会在该元素上放置一个类。
像这样的东西:
$('*').click(function(){$(this).toggleClass('debug')});
这实际上有效,除了它为所有元素切换“调试”。
例如:
<body>
<div id='3'>
<div id='2'>
<div id='1'></div>
</div>
</div>
</body>
如果我点击
,它会向
添加一个名为“debug”的类代码> 和<代码>发生的情况是,当您单击
到目前为止,我有:
window.v = [];
$('*').click(function(){window.v.push(this)});
接下来,它是:
$(window.v[0]).toggleClass('debug');
不幸的是,当这个:
$(window.v[window.v.length]).toggleClass('debug');
...或上面执行时,它不会执行任何操作,它会将“debug”类放在 body 标记上 所以
,我是。不确定使用数组是否是最佳途径。是否有其他人对如何普遍单击任何元素并将调试类放在其上有任何想法
?
I'm building a debugging tool for myself. What I want it to do is place a class on any element whenever it's clicked.
Something like this:
$('*').click(function(){$(this).toggleClass('debug')});
That actually worked, except that it toggles "debug" for ALL elements.
For example:
<body>
<div id='3'>
<div id='2'>
<div id='1'></div>
</div>
</div>
</body>
If I clicked on <div id="1">
, it will add a class called "debug" to <div id="2">
and <div id="3">
.
What's happening is when you click on <div id="1>
, it counts as a click to all 3, because technically, all divs were clicked. So I've thought about having an array that holds all the HTML elements.
So far, I have:
window.v = [];
$('*').click(function(){window.v.push(this)});
Following that, it's:
$(window.v[0]).toggleClass('debug');
Unfortunately, when this:
$(window.v[window.v.length]).toggleClass('debug');
...or the above executes, it doesn't do anything. Sometimes, it places the "debug" class on the body tag.
So, I'm not exactly sure if using an Array is the best route for this. Does anyone else have any ideas on how to universally click on any element and place the debug class on it?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这样做:
将点击处理程序绑定到所有 DOM 元素是一个坏主意。相反,将一个单击处理程序绑定到
window
对象。您可以这样做,因为点击事件会冒泡(DOM 树)。为了确定单击了哪个元素,请使用e.target
。就这么简单
:)
现场演示: http:// jsfiddle.net/Ucpzq/1/
Do this:
Binding click handlers to all DOM elements is a bad idea. Instead, bind one single click handler to the
window
object. You can do this because click events bubble up (the DOM tree). In order to determine which element was clicked, usee.target
.Simple as that
:)
Live demo: http://jsfiddle.net/Ucpzq/1/
取消气泡:
Cancel the bubble: