jQuery找到“选择器”

以下是我的代码

HTML

Hello !!

Javascript

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

我需要捕获我在上面的代码中传递给jQuery函数的参数,我想将输出打印为#content .child

谢谢 !!

为提供此function的click,focus,..事件编写自己的包装器。 编写这样的包装器是相当简单的。 这是一种方式:

 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 }); }; 

您的事件处理函数现在获得两个参数而不是一个。 第一个是事件,第二个是用于绑定此事件的选择器。

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

使用闭包将其包装起来的优点是,您可以将多个单击事件绑定到具有不同选择器的同一元素,并且它们将一起工作。

看一个例子 。

通常你会使用selector ,但在这种情况下, this没有选择器。 您可以使用:

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

当然,这将为每个孩子显示相同的选择器,而不是所有有用的(可能是调试)。 你可以更简单,请注意:

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

工作示例: http : //jsfiddle.net/cmuTv/

除了Kobi的答案,通常不可能。 这有点像问“给定以下循环如何重新获得原始数组?”

 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'? */ ); } 

很明显,在这种情况下,只能给出原始数组。 但可能不太清楚的是,在你的情况下也是如此。

这是因为对.each()的调用基本上变成了对.each()的调用, .each()基本上只是围绕每个匹配元素的for循环。 当您查看该集合中的单个元素时,无法再次返回原始集合。