jQuery finding “selector”

2019-07-15 07:45发布

问题:

following is my code

HTML :

<div id = "content" >
  <div class = "child" >Hello !! </div>
</div>

Javascript :

$(function() {
  $('#content .child').click(function() {
          //print the selected jQuery parameters
  });
});

I need to capture parameters which I pass to jQuery function in above code, I want to print the output as #content .child.

Thank you !!

回答1:

Write your own wrappers for click, focus, .. events that provide this functionality. Writing such a wrapper is fairly trivial. Here's one way:

jQuery.fn.addClick = function(fn) {
    var selector = this.selector; // capture the selector here
    this.click(function(event) { // write a wrapper for the click handler
        fn(event, selector); // call the user's handler and pass it the selector
    });
};

Your event handler function now gets two params instead of one. First is event, and the second is the selector that was used to bind this event.

$("#content .child").addClick(function(e, selector) {
    alert(selector); // "#content .child"
});

The advantage of wrapping it up with closures is that you can bind multiple click events to the same element with different selectors, and they will all work together.

See an example.



回答2:

Normally you'd use selector, but in this context, this has no selector. You might use:

var div = $('#content .child');
div.click(function() {
    alert(div.selector);
});

Of course, that will show the same selector for each child, and not all that useful (maybe debugging). You can go simpler, mind you:

var selector = '#content .child';
$(selector).click(function() {
    alert(selector);
});

Working example: http://jsfiddle.net/cmuTv/



回答3:

Apart from Kobi's answer, it's not generally possible. It's kind of like asking "given the following loop how do I get the original array back again?"

var array = [1, 2, 3, 4, 5];
for (i = 0; i < array.length; i++) {
    var a = array[i];
    alert( /* how do I get the original array given only 'a'? */ );
}

It's clear that in this case, you can't get the original array back given only a. But what might not be clear is that the same is true in your case as well.

This is because a call to .click() is essentially turned into a call to .each() and that's basically just a for loop around each of the matched elements. When you're looking at a single element in that collection, there's no way to get the original collection back again.