开发者

Hot to get DOM or jQuery element by mouse?

开发者 https://www.devze.com 2023-02-21 07:50 出处:网络
How to get DOM or jQuery element by mouse click? For example I have the next code: $(\"*\").mouseup( function()

How to get DOM or jQuery element by mouse click? For example I have the next code:

$("*").mouseup(
 function() 
 {
    var clickedElement = ??????????开发者_如何学Python?????
 }
);

So, how to init 'clickedElement' variable? Thank you.


Inside an event handler, this refers to the DOM element the event was raised on.

$("*").mouseup(function() {
    var clickedElement = this;
});

To get a jQuery element, just pass this to jQuery.

But: It would be much much much better to use event delegation, instead of binding an event handler to every element. You can get the origin of the event with event.target:

$(document).mouseup(function(event) {
    var clickedElement = event.target;
});

And a further note: This will not necessarily give you the clicked element, but the element over which the mouse button was released, which can be different from the element the button was pressed. You might want to bind to the click event.


I also suggest to read a jQuery tutorial where these basics are covered.


If you don't want to attach an event to every DOM element (which I wouldn't recommend)...

$(document).mouseup(function(event) {
   var clickedElement = event.target;
});

jsFiddle.

Here, any element's event will bubble up all the way to document, where it will be handled, and the originating element that started the event will be in event.target.


Use this. i.e.:

$("*").mouseup(  function()   {     
    var clickedElement = this; //HTML DOM Element
    var $clickedElement = $(this); //jQuery Wrapped HTML DOM Element
} ); 
0

精彩评论

暂无评论...
验证码 换一张
取 消