当前位置: 动力学知识库 > 问答 > 编程问答 >

Detecting a DOM element using jquery

问题描述:

I want to detect what DOM element i have clicked on like Firebug does. So far, Google has only turned up with results about detecting a deleted DOM element.

Please tell me if that is possible in jQuery. And if not, which third party tools/libraries can be used to achieve the goal.

网友答案:

You could use this, although it may not be very performant depending on the size of the DOM.

$('*').on('click', function () {
    var clickedElement = this;
});
网友答案:

You can get all tags inside the BODY tag using the following (which binds a listener to change border on mouseover, mouseout and retrieve the element's ID when clicked):

var elems = $("body *");

$(elems).each(function() {
    var elem = this;

    $(elem).bind("mouseover", function() {
        $(elem).css("border", "1px solid #00f");
    });        

    $(elem).bind("mouseout", function() {
        $(elem).css("border", "none");
    });        

    $(elem).bind("click", function() {
        $("#elements").html($(elem).attr("id"));
    });
});

​ Example: jsfiddle example here

网友答案:

You can try this:

JQuery Code

$(document).ready(function(){
     $('*').on('click', function(){
          console.log(this);
     });
});

Be sure you add the JQuery in your document. Then try above. check the console on firebug.

网友答案:
$('body').on('click', function () {
    var me = this;
    // you can also get the id like
    var id = this.id;
    // you can also get the class
    var classes = $(this).attr('class');
    // and more
});

if you want to prevent page reload/ default submission then use preventDefault() like below:

$('body').on('click', function (e) {
    e.preventDefault();

    var me = this;
    // you can also get the id like
    var id = this.id;
    // you can also get the class
    var classes = $(this).attr('class');
    // and more
});

For dynamic element you need a delegate event handler (aka live) which can also accomplish by .on() like below

$('body').on('click', '*', function(e) {
  // you code like above approach
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: