Is there a way to get jQuery selector expression text?
I have an array of selectors like :
var arr = [".discuss .title .post", ".post .desc" , ".eventlist .event"];
I want to loop through this array and attach a click event on it.
for(var i in arr){
$(arr[i]).click(function(){
//here I need the selector i.e. arr[i] expression - for some css work
});
}
Is there a way by which I can get this selector expression inside the click callback function? I went through this post which has similar problem 开发者_StackOverflow社区: How do I get a jQuery selector's expression as text?
But as said there, I couldn't find any "selector" attribute of jQuery object. I tried this way:
for(var i in arr){
$(arr[i]).click(function(){
console.log(jQuery(this).attr('selector')); //This gives undefined
});
}
Any help?
The correct syntax is $('.something').selector
. However, .selector
only works when a selector string is explicitly supplied - but there is no selector in $(this)
.
One workaround is to save a copy of the selector in a function surrounding the click
function:
for (var i = 0; i < arr.length; i++) { // (Don't use "for-in loop" for arrays)
(function (selector) { // 2. a copy is saved as the argument "selector"
$(selector).click(function () {
console.log(selector);
});
}) (arr[i]); // 1. Pass in the selector
}
Another option is to compare $(this)
to each selector in your array, using .is()
:
$(arr.join(',')).click(function () { // a quick way to select all selectors
var selector;
for (var i = 0; i < arr.length; i++) {
if ($(this).is(arr[i])) {
selector = arr[i];
break;
}
}
console.log(selector);
});
You can at least get the class value of each selected element:
$(this).attr("class");
Doesn't this provide sufficient info for what you intend to do?
I don't seem to get any error, its as though there is no .click()
event, example here
But if you split your array and attach a click to every item in your array it seems to work for me.
// Trouble is you will attach two click's to a class="post" item:
var arr = [".discuss .title .post", ".post .desc" , ".eventlist .event"];
for(var a in arr){
var ar = arr[a].split(' ');
for(var i in ar){
$(ar[i]).click(function(e){
e.preventDefault();
var href = $(this).attr('href');
var sele = $(this).attr('selector');
console.log(href);
console.log(sele);
alert("HREF: "+href+" - Selector: "+sele);
});
}
}
Take a look at it in action here along with a solution to stopping adding two clicks.
精彩评论