javascript - 将 jquerys .toggle() 重写为 .click() 函数

标签 javascript jquery html url-rewriting toggle

<分区>

当单击带有类“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>

最佳答案

你会改用旗帜

$(".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);
});

关于javascript - 将 jquerys .toggle() 重写为 .click() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29133030/

相关文章:

javascript - 我在 Flask 应用程序中使用 $.(get) 请求时遇到的 JavaScript 问题

html - 调整浏览器大小时保持宽高比

javascript - 使用 td 而不是 nth-child 来抓取表

javascript - 避免 jQuery 静默失败的模式

javascript - 如何在动画/过渡中间暂停

html - 在新行上显示来自 asp :TextBox 的所有条目

html - 用于选择包含随机数的 html id 的 Xpath

javascript - 在 redux 的 React 16 中替换 componentWillRecieiveProps?

Javascript:创建带有参数数量文本框的表单(TinyMCE)

javascript - 为什么设置 textContent 会导致布局抖动?