jQuery查找“选择器" [英] jQuery finding "selector"
问题描述
以下是我的代码
HTML :
<div id = "content" >
<div class = "child" >Hello !! </div>
</div>
JavaScript :
$(function() {
$('#content .child').click(function() {
//print the selected jQuery parameters
});
});
我需要捕获在上面的代码中传递给jQuery
函数的参数,
我想将输出打印为#content .child
.
I need to capture parameters which I pass to jQuery
function in above code,
I want to print the output as #content .child
.
谢谢!!
推荐答案
编写自己的包装,以提供提供此功能的click,focus等事件.编写这样的包装器是相当琐碎的.这是一种方法:
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"
});
使用闭包将其包装起来的好处是,您可以使用不同的选择器将多个click事件绑定到同一元素,并且它们将一起工作.
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.
查看示例.
这篇关于jQuery查找“选择器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!