如何将 jquery 对象传递给函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1476516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a jquery object to function?
提问by
I am trying to write a generic code
我正在尝试编写通用代码
var rodd = $('#checkBox');
I want to pass rodd to a function and check if it is checked
我想将 rodd 传递给一个函数并检查它是否被选中
Callme(rodd);
$(rodd).click(function() {
Callme(this);
});
function Callme(rodd){
if(this.checked){
// do some behavior
}
}
采纳答案by cletus
If rodd
is a jQuery object:
如果rodd
是 jQuery 对象:
function Callme(rodd) {
if (rodd.is(":checked")) {
// ...
}
}
or:
或者:
function Callme(rodd) {
if (rodd[0].checked) {
// ...
}
}
回答by Marius
This should work:
这应该有效:
//Assuming rodd is a jquery element
Callme(rodd);
rodd.click(function() {
Callme($(this));
});
function Callme(rodd){
if(this.is(":checked"){
// do some behavior
}
}
remember that the event listener has this pointing at the DOM element, not the jquery element. Therefore you need to convert this into a jquery element, using the $(this) expression.
请记住,事件侦听器将 this 指向 DOM 元素,而不是 jquery 元素。因此,您需要使用 $(this) 表达式将其转换为 jquery 元素。
回答by Russ Cam
Looking at your code, your passing in a jQuery object, rodd
, into a function to return a jQuery object $(rodd).click...
查看您的代码,您将一个 jQuery 对象rodd
传入一个函数以返回一个 jQuery 对象$(rodd).click...
It might be easier to do
这样做可能更容易
$('#checkBox').click(Callme);
function Callme(rodd){
if(this.checked){
// do some behavior
}
}
or
或者
$('#checkBox').click(Callme);
function Callme(rodd){
if($(this).is(':checked')){
// do some behavior
}
}
this also does away with the anonymous function event handler that is only executing Callme()
passing in the event target. Working Demohere.
这也消除了仅执行Callme()
传入事件目标的匿名函数事件处理程序。工作演示在这里。
EDIT:
编辑:
Currently, Callme(rodd)
above expects a HTMLElement object
to be passed in. If you want to be able to pass in a jQuery object, simply change to this
目前,Callme(rodd)
上面期望HTMLElement object
传入a 。如果您希望能够传入 jQuery 对象,只需更改为 this
$('#checkBox').click(function(event) {
Callme($(event.target));
});
function Callme(rodd){
if(rodd.is(':checked')){
alert('checked');
}
}
although personally, I would keep it as an element to be passed in and do the wrapping in the Callme
function. you might want to consider prefixing the rodd
parameter with $
to make it obvious that a jQuery object is expected.
尽管就我个人而言,我会将其保留为要传入的元素并在Callme
函数中进行包装。您可能需要考虑在rodd
参数前加上前缀,$
以明确表示需要 jQuery 对象。