我有一个 if 语句不能正常工作,我相信这是因为使用了“this”,但我不确定如何修复它。这是代码:
$('.enlarge').click(function() {
var id = $(this).find(".enlarged_txt").attr('id');
$('#full_image').animate({
height: "100%"
}, 300, function() {
if ( $(this).hasClass("v") ) {
$('#full_image img').attr('src','http://www.klossal.com/klossviolins/instruments/violins/full/' + id + '.jpg');
fadeIn($('#full_image img'));
$("#close_2").css({
display: "block"
});
$("#close").css({
display: "block"
});
}
});
});
<div class="enlarge v" style="float:right;margin-right:70px;margin-top:5px;">
<img class="enlarged_unselected" style="float:left;margin-top:6px;" src="http://www.klossal.com/klossviolins/elements/fullscreen_unselected.png"/>
<img class="enlarged_selected" style="float:left;display:none;" src="http://www.klossal.com/klossviolins/elements/fullscreen_selected.png"/>
<div id="ChasHunnicutt_1928" style="float:left;padding-left:8px;" class="enlarged_txt">Enlarge Image</div>
</div>
最佳答案
是的,这个里面的this
有问题。
因为第二次使用 this
时,您在 animate(
调用中的新函数中使用了它。这次您使用 this
this
引用 ( according to this jQuery doc )“正在动画的 DOM 元素。”
如果您想引用由 .click(
处理程序传入的原始 this
到您的顶级函数(它引用被单击的 DOM 元素),您需要首先保存它,然后用保存的对原始 this
的引用替换第二个 this
。
关键字很有趣。
像这样:
$('.enlarge').click(function() {
var jthis = this; // save the reference to the $('.enlarge') that was clicked
var id = $(this).find(".enlarged_txt").attr('id');
$('#full_image').animate({
height: "100%"
}, 300, function() {
if ( $(jthis).hasClass("v") ) {
$('#full_image img').attr('src','http://www.klossal.com/klossviolins/instruments/violins/full/' + id + '.jpg');
fadeIn($('#full_image img'));
$("#close_2").css({
display: "block"
});
$("#close").css({
display: "block"
});
}
});
});
这应该可以解决 this
的问题。
关于javascript - 在 if 语句中使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14625284/