编辑:上面的建议不是这个问题的答案。请参阅tymeJV的回答。
我的表单上有一个优惠代码字段,但一旦申请,我希望它停止。目前,您可以继续输入优惠代码,并且会不断折扣价格。
如何阻止这种情况发生?
$("#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();
答案 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)
$('a.remove_item').on('click',function(e) {
alert('clicked');
$('a.remove_item').off('click');
});
$(document).ready(function(){
$("#offerapply").one('click', function () {
// your code here
})
});
$.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 */ });
$('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();