提问人:Vahid 提问时间:10/14/2011 最后编辑:Lightness Races in OrbitVahid 更新时间:5/29/2019 访问量:99868
jQuery 将 $(this) 传递给函数
jQuery Passing $(this) to a Function
问:
我有这样的代码行:
$(this).parent().parent().children().each(function(){
// do something
});
效果很好。但是我需要多次运行这些行。 所以我创建了一个函数并将 $(this) 参数传递给一个函数:
myFunc( $(this) );
function myFunc(thisObj) {
thisObj.parent().parent().children().each(function(){
// do something
});
}
但这样一来,它就没有奏效了。
答:
83赞
erimerturk
10/14/2011
#1
您可以查看此链接。
$("#f").click(function() {
myFunc($(this));
})
function myFunc(thisObj) {
thisObj.parent().parent().children().each(function() {
alert("childs")
});
}
<div id="wordlist">
<div id="a"></div>
<div id="b">
<div id="e"></div>
<div id="f">child</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
17赞
Muhammad Tahir
5/30/2015
#2
jQuery将自动调用具有正确上下文集的函数。
$('#button').on('click', myFunction);
function myFunction() {
var that = $(this);
console.log(that);
}
2赞
Krzysztof Przygoda
3/21/2018
#3
如果您在无冲突模式下工作(即超出全局范围),则其中一种可能性是:
jQuery.noConflict();
(function ($) {
$('#button').on('click', myFunction);
}(jQuery));
// or
jQuery('#button').on('click', myFunction);
function myFunction() {
var that = jQuery(this);
console.log(that);
}
-1赞
Shaun O'Toole
5/29/2019
#4
您可以将 id 传递给函数。在函数内部使用您的循环。
myFunc(this.id);
function myFunc(thisid) {
$("#" + thisid).parent().parent().children().each(function(){
// do something
});
}
我通常会在函数之外进行循环,如下所示:
$(this).parent().parent().children().each(function(){
myFunc(this.id)
});
function myFunc(thisid) {
// do something example
$("#" + thisid).html("Yay, i changed the html for element: " + thisid);
}
评论