如何使 Javascript 函数 changeImage() 删除项目

How to make Javascript function changeImage() remove item

按下按钮时会出现两个功能。第一个功能是 "item1" 添加到购物车,第二个功能是按钮图像从 "add.png" 更改为 "minus.png"。将按钮切换到 "minus.png" 后,期望的结果是将商品从购物车中移除,如果再次按下按钮,图像将转换为原始 "add.png"。 http://simplecartjs.org/documentation/simplecart-item-remove

按钮示例:http://jsfiddle.net/9kmun19z/

<img id="button" onclick="addbeat(event);changeImage()" name="item1" src="add.png"/>

<script>
function addbeat(event) {
simpleCart.add({
     name: event.target.name,
     price: .99
 });
}
function changeImage() {
    var image = document.getElementById('button');
    if (image.src.match("minus")) {
        image.src = "add.png";
    } else {
        image.src = "minus.png";
simpleCart.item.remove();({
     name: event.target.name,
     price: .99
 });
    }
}
</script>

为什么不只使用两个按钮来满足您的需求。

为两个按钮绑定不同的功能;

使用 css 显示:none/block 控制显示哪个按钮。

那一切就OK了

你可以使用jquery,它会对你有很大帮助。

看这个例子:

<img id="button" data-product-id="XYZ" name="items" src="add.png"/>


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

您似乎将简单的购物车删除放在了错误的分支中 - 您想要在显示减号按钮时删除该项目

function changeImage() {
 var image = document.getElementById('button');
 if (image.src.match("minus")) {
   simpleCart.item.remove();({
     name: event.target.name,
     price: .99
     });
   image.src = "add.png";
   } else {
   image.src = "minus.png";
   }

}

花了一些时间,但我能够使用 Kadugedboy 推荐的 Jquery 以及函数中的 quantity=1 和 quantity=-1 获得预期的效果,有一件事你必须要做的是确保安装了 Jquery 1.7 或更低版本,因为他们删除了较新版本中的 toggle() 功能。

<img class="button" data-product-id="XYZ" 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", "minus.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>