下面是一个很好的例子
$(".multi-select").change(function() {
$(this).parent().parent().addClass("glow");
} );.glow {
box-shadow: inset 0px 10px 10px 3px rgba(255, 0, 0, 1) !important;
box-sizing: border-box;
display: block;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="slides-containter">
<div class="slide-container" id="slide_34">
<div class="zoom-container">
<span class="zoom-caption">
<h3>
<input class="multi-select" id="slide_select_34" name="ids[]" type="checkbox" value="34" />
</h3>
</span>
<img alt="4c730521b21310758a4809d7b56feec5" src="http://foobar.tuxpartei.ch/foobar.png" />
</div>
</div>
但由于某些原因,如果我尝试将其拆分为回调函数,它将不起作用,例如
function glow_it() {
$(this).parent().parent().addClass("glow");
};
$(".multi-select").change(function() {
glow_it();
}.glow {
box-shadow: inset 0px 10px 10px 3px rgba(255, 0, 0, 1) !important;
box-sizing: border-box;
display: block;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="slides-containter">
<div class="slide-container" id="slide_34">
<div class="zoom-container">
<span class="zoom-caption">
<h3>
<input class="multi-select" id="slide_select_34" name="ids[]" type="checkbox" value="34" />
</h3>
</span>
<img alt="4c730521b21310758a4809d7b56feec5" src="http://foobar.tuxpartei.ch/foobar.png" />
</div>
</div>
我想我应该把这个传递给它。应该怎么做?
提前谢谢你。
发布于 2015-01-10 02:13:58
这是因为当您调用glow_it()函数时,选择器的上下文丢失,即$(this)不再引用change事件的触发元素,而是引用窗口对象,即$(window)。要解决这个问题,请将$(this)作为变量传递给函数:
function glow_it(t) {
$(t).parent().parent().addClass("oxo");
};
$(".multi-select").change(function() {
glow_it(this);
});p/s:还存在语法错误,因为在)事件的最后一行中省略了结束括号.change()。
见这里的概念证明:http://jsfiddle.net/teddyrised/h0euqvf0/7/
Update:或者,您可以调用glow_it()函数作为.on('change', [handler])中的第二个参数,以保留上下文,正如@adeneo在他的评论中建议的那样:
$(".multi-select").on('change', glow_it);在jQuery .on()文档中很好地解释了为什么这样做的原因:
当jQuery调用处理程序时,
this关键字是对传递事件的元素的引用;对于直接绑定的事件,这是附加事件的元素,而对于委托的事件,则是匹配selector的元素。(注意,如果事件是从子代元素中冒泡的,那么this可能不等于event.target。)若要从元素中创建jQuery对象,以便可以与jQuery方法一起使用,请使用$( this )。
参见演示:http://jsfiddle.net/h0euqvf0/5/
发布于 2015-01-10 02:14:31
在var中声明$(this)并将其作为参数传递。
function glow_it(multiSelect ) {
multiSelect.parent().parent().addClass("oxo");
};
$(".multi-select").change(function() {
var multiSelect = $(this);
glow_it(multiSelect );
)};发布于 2015-01-10 02:19:19
另一种选择是使用jquery proxy方法。它允许您定义调用上下文。在这种情况下,由于您可以使用glow_it作为change处理程序,所以有些东西是无用的,但是在其他一些情况下,这可能更好地提供这个选项。
$(".multi-select").change(function() {
$.proxy(glow_it, this)();
});https://stackoverflow.com/questions/27872143
复制相似问题