我有这个代码:
<div id="product_<?php echo $product->id; ?>"></div>
这是ajax js代码:
$(function () {
$('.expand').on('click', function (e) {
e.preventDefault();
var token = "<?php echo $this->security->get_csrf_token_name(); ?>";
var hash = "<?php echo $this->security->get_csrf_hash(); ?>";
var productID = $(this).data("id");
$.ajax({
type: 'GET',
dataType: 'html',
url: 'marketplaces/marketplaces/test_expand',
data: {
product_id: productID,
token: hash
},
beforeSend: function () {
},
success: function (data, textStatus) {
$("#product_" + productID).html(data);
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
},
complete: function () {},
});
});
});
这个按钮:
<div data-id="<?php echo $product->id; ?>" class="expand">
<a href="#" class="bt btn-primary btn-sm">Offers
<i class="fas fa-chevron-down"></i>
</a>
</div>
当我用id=product_(ID)
点击按钮div时,它会显示来自ajax的数据。它在工作!当我再次点击按钮时,我想隐藏这个div!
怎么可能?非常感谢。
您可以使用自定义代码设置条件,以实现显示-隐藏功能。
这是示例代码:
$(function () {
$('.expand').on('click', function (e) {
e.preventDefault();
var currBoxObj = this;
var token="<?php echo $this->security->get_csrf_token_name(); ?>";
var hash="<?php echo $this->security->get_csrf_hash(); ?>";
var productID = $(this).data("id");
if(!$(currBoxObj).hasClass("showingblock")){
$.ajax({
type: 'GET',
dataType: 'html',
url: 'marketplaces/marketplaces/test_expand',
data:
{
product_id: productID,
token: hash
},
beforeSend: function () {
},
success: function (data, textStatus) {
$(currBoxObj).addClass("showingblock");
$("#product_"+productID).show();
$("#product_"+productID).html(data);
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
},
complete: function () {
},
});
}else{
$("#product_"+productID).hide();
$(currBoxObj).removeClass("showingblock");
}
});
});
$('[data id=product_id]'(.hide((;
我认为你可以像这样使用代码。希望能对你有所帮助。
打开元素时,应该向元素添加一个类
$("#product_" + productID).addClass('is-open')
然后在第二次点击(ajax调用上方(时检查它是否有类
if ($("#product_" + productID).hasClass('is-open')) {
$("#product_" + productID).hide().removeClass('is-open')
return
}
如果你想在打开一个之前关闭所有,那么做起来很琐碎:
$('.is-open').hide().removeClass('is-open')