点击我改变所选div的css,如下所示:
$(".like-grid-span").click(function() { if ($(this).css('color') == "rgb(0,0)") { $(this).css({ color: 'blue',transition: 'all .45s' }); $('.like-count').html(data); $(this).prop('title','Rated as Good'); } else { $(this).css({ color: 'rgb(0,0)',transition: 'all .45s' }); $(this).prop('title','Rate as Good'); } });
我刚刚在onclick函数中引入了ajax请求,并在成功回调中添加了其余代码,但是我的this关键字(即引用当前选中的div)现在不能正常工作,我知道它可能是指ajax函数现在但我怎么还能用它来引用选中的div?或者有其他选择吗?
$(".like-grid-span").click(function() { var selected_offer_id = $(this).closest("ul.amenities").data('id'); $.ajax({ url: "/apexrealestates/goods/goodmechanism.PHP",type: "POST",data: { user_id: 1,offer_id: selected_offer_id },success: function(data) { if ($(this).css('color') == "rgb(0,0)" && data != false) { $(this).css({ // this is the my this keyword I'm talking about color: 'blue',transition: 'all .45s' }); $('.like-count').html(data); $(this).prop('title','Rated as Good'); } else { $(this).css({ color: 'rgb(0,transition: 'all .45s' }); } },error: function(data) { alert("phat gea"); } }); });
这是我的HTML:
<div class="row"> <div class="listing_tile item col-sm-4"> <div class="options"> <a data-placement="bottom" data-toggle="popover" data-title="Login" data-container="body" type="button" data-html="true" href="#" id="login">Login</a> <div id="popover-content" class="hide"> </div> </div> <div class="image"> <a href="./property/detail.PHP"> <span class="btn btn-default"><i class="fa fa-file-o"></i> Take a Look</span> </a> <img src="img/property2.jpg" alt="" /> </div> <div class="favt-grid-div" title="Add to Wishlist"> <i class="fa fa-star"></i> </div> <div class="price"> <i class="fa fa-home"></i>For Sale <span>PKR 2500000</span> </div> <div class="info"> <h3 class="text-center"> <a href="#">Apartment in Bahria</a> <small><?= getExcerpt('556-Safari villas bahria town Lahore'); ?></small> </h3> <h4 class="text-center text-danger"><b>Lahore</b></h4> <ul class="amenities" data-id="2"> <li><i class="fa fa-arrows"></i> 45 Sq-Ft</li> <li title="click to Rate"><span class="like-grid-span"><i class="fa fa-thumbs-o-up"></i></span><span class="like-count">26</span> Likes</li> </ul> </div> </div> </div>
帮助会很好,谢谢.
解决方法
将此引用存储在变量中,然后在成功回调方法中使用它
$(".like-grid-span").click(function() { var _self = $(this); //Store reference $.ajax({ success: function(data) { //Use the variable _self.css({ }); } }); });
另外,您可以使用上下文,它在回调中设置this的值.
$.ajax({ context: this,});
编辑,取消绑定并绑定点击处理程序
function likeClickHandler() { var _self = $(this); //Unbind click handler _self.off('click') $.ajax({ success: function(data) { //Use the variable _self.css({ }); //Bind Click handler _self.on('click',likeClickHandler); } }); } $(".like-grid-span").on('click',likeClickHandler);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。