【问题标题】:Rewrite jquerys .toggle() into a .click() function [duplicate]将 jquery .toggle() 重写为 .click() 函数[重复]
【发布时间】:2015-05-21 21:14:21
【问题描述】:

当点击带有类“button”的“add.png”图像时,它会将商品添加到购物车并转换为“remove.png”当再次点击它时,它将从购物车中删除商品并转换回原来的“添加.png"

这适用于 Jquery 1.7 及更低版本,但 .toggle() 功能已从较新版本的 Jquery 中删除。

期望的结果是执行相同的任务,但使用 .click() 而不是 .toggle()

<img class="button" data-product-id="Item1" src="add.png" />

<script>
$(".button").toggle(function(){
    //first functon here
    simpleCart.add({
     name: $(this).attr("data-product-id"),
     price: .99,
	 quantity: 1
    });
    //we set src of image with jquery
    $(this).attr("src", "remove.png");
},function(){
    //second function here
    //simplecart remove function here, this isjust example, adjust with your code
	simpleCart.add({
     name: $(this).attr("data-product-id"),
     price: .99,
	 quantity: -1
    });
    $(this).attr("src", "add.png");
});

</script>

【问题讨论】:

    标签: javascript jquery html rewrite toggle


    【解决方案1】:

    你会使用一个标志来代替

    $(".button").on('click', function(){
        var flag = $(this).data('flag');
    
        simpleCart.add({
            name     : $(this).attr("data-product-id"),
            price    : .99,
            quantity : (flag ? 1 : -1)
        });
    
        $(this).attr("src", flag ? "remove.png" : "add.png")
               .data('flag', !flag);
    });
    

    【讨论】:

    • 我交换了图像和数量值,这很有效!谢谢 Adeneo
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2014-02-08
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多