jQuery,Click上的Select(any all *)元素(jQuery, Select (any all *) element on Click)

编程入门 行业动态 更新时间:2024-10-23 11:27:30
jQuery,Click上的Select(any all *)元素(jQuery, Select (any all *) element on Click)

我正在为自己构建一个调试工具。 我想要它做的是在任何元素被点击时放置一个类。

像这样的东西:

$('*').click(function(){$(this).toggleClass('debug')});

这实际上是有效的,除了它切换所有元素的“调试”。

例如:

<body> <div id='3'> <div id='2'> <div id='1'></div> </div> </div> </body>

如果我点击<div id="1"> ,它会将一个名为“debug”的类添加到<div id="2">和<div id="3"> 。

发生的事情是当你点击<div id="1> ,它被视为对所有3的点击,因为从技术上讲,所有的div都被点击了。所以我考虑过拥有一个包含所有HTML元素的数组。

到目前为止,我有:

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.

最满意答案

做这个:

$( window ).click(function ( e ) { $( e.target ).toggleClass( 'debug' ); });

将点击处理程序绑定到所有 DOM元素是一个坏主意。 而是将一个单击处理程序绑定到window对象。 你可以这样做,因为点击事件冒泡(DOM树)。 要确定单击了哪个元素,请使用e.target 。

很简单:)

现场演示: http //jsfiddle.net/Ucpzq/1/

Do this:

$( window ).click(function ( e ) { $( e.target ).toggleClass( 'debug' ); });

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, use e.target.

Simple as that :)

Live demo: http://jsfiddle.net/Ucpzq/1/

更多推荐

本文发布于:2023-08-06 18:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1452854.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   Click   jQuery   element   Select

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!