jquery这回归奇怪的反应

时间:2014-10-19 21:40:20

标签: javascript jquery

我有以下功能来切换"添加到购物车"按钮

function addOrRemoveFromCart(){
    alert($(this).val)
    if ($(this).hasClass("add_to_cart")){
        alert('yes');
        $(this).prop('value', 'Remove from Cart');
        $(this).removeClass("add_to_cart");
        $(this).addClass("remove_from_cart");
    }
    else{
        alert('no');
        $(this).prop('value', 'Add to Cart');
        $(this).addClass("add_to_cart");
        $(this).removeClass("remove_from_cart");
    }
}

这是我的按钮

<input id="069874" class="add_to_cart button" type="button" onclick="addOrRemoveFromCart()" value="Add To Cart">

$(this).hasClass("add_to_cart")返回false

$(this).val返回一个与值

无关的非常长的输出

3 个答案:

答案 0 :(得分:1)

您需要将此功能设置为“添加到购物车”按钮的绑定。

因此:

$('add_to_cart').on('click', function(){
    if ($(this).hasClass("add_to_cart")){
        alert('yes');
        $(this).prop('value', 'Remove from Cart');
        $(this).removeClass("add_to_cart");
        $(this).addClass("remove_from_cart");
    }
    else{
        alert('no');
        $(this).prop('value', 'Add to Cart');
        $(this).addClass("add_to_cart");
        $(this).removeClass("remove_from_cart");
    }
return false; // or preventdefault
}
});

此外 - 此元素的ID无效。 html中元素的ID不能以数字开头。


编辑:请注意,使用内联'onclick'属性被认为是不好的做法,应该避免使用。

答案 1 :(得分:1)

.val是一个功能

致电$(this).val()获取值

答案 2 :(得分:0)

<input id="069874" class="add_to_cart button" type="button" onclick="addOrRemoveFromCart.call(this)" value="Add To Cart">

$(this).val提醒函数代码。你必须打电话给它!更改为$(this).val()