一旦输入成功的折扣代码,如何使点击事件停止?

时间:2013-07-18 20:51:16

标签: javascript jquery

编辑:上面的建议不是这个问题的答案。请参阅tymeJV的回答。

我的表单上有一个优惠代码字段,但一旦申请,我希望它停止。目前,您可以继续输入优惠代码,并且会不断折扣价格。

Js Fiddle Demo

如何阻止这种情况发生?

$("#offerapply").click(function () {
if ($("input[name='offercode']").val().toLowerCase() == "discount10")  {
    price = (price / 10) * 9;
    $("#offermsg").text('Thank you. Your 10% discount has been applied.');
}
else {
    $("#offermsg").text('Sorry, that Offer Code was not recognised.');
}
calculate();

4 个答案:

答案 0 :(得分:6)

if真实区块内,取消绑定以防止多次折扣:

if ($("input[name='offercode']").val().toLowerCase() == "discount10")  {
    price = (price / 10) * 9;
    $("#offermsg").text('Thank you. Your 10% discount has been applied.');
    $(this).off();
}

答案 1 :(得分:3)

查看 one jquery方法。所以你可以尝试这段代码:

$("#offerapply").one('click', function () {
    // your code here
})

答案 2 :(得分:1)

Demo - Approach #1

$('a.remove_item').on('click',function(e) {
    alert('clicked');
   $('a.remove_item').off('click');
});

Demo - Approach #2

$(document).ready(function(){
    $("#offerapply").one('click', function () {
        // your code here
    })
});

Demo - Approach #3

$.fn.liveAndLetDie = function(event, callback) {
    var sel = this.selector;
    function unbind() { $(sel).die(event, callback).die(event, unbind); }
    return this.live(event, callback).live(event, unbind);
};

$('your elements').liveAndLetDie('click', function(e) { /* do stuff */ });

Demo - Approach #4

$('your element').live('click',function(e) {
     $('your element').die('click'); // This removes the .live() functionality
});

答案 3 :(得分:0)

一个简单的解决方案就是存储是否已应用商品代码,但如上所述,请确保您还在进行服务器端验证。

var offercodeApplied = false;

$("#offerapply").click(function () {
if (offercodeApplied) {
    $("#offermsg").text('Offer code already applied.');
}
else if ($("input[name='offercode']").val().toLowerCase() == "discount10")  {
    offercodeApplied = true;
    price = (price / 10) * 9;
    $("#offermsg").text('Thank you. Your 10% discount has been applied.');
}
else {
    $("#offermsg").text('Sorry, that Offer Code was not recognised.');
}
calculate();