lor*_*afs 1 javascript jquery if-statement this
我有一个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>
Run Code Online (Sandbox Code Playgroud)
是的,这里有一个问题this.因为第二次this使用它时会在animate(调用内的新函数中使用它.这一次使用this的this引用(根据本jQuery的文档)的"被动画DOM元素."
如果你想引用this传入的原文.click(您的顶级函数(引用被单击的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"
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
哪个应该解决问题this.