9

I have this function that disables the input after user clicks:

$('.click-off').click(function () {
    var btn = this;
    setTimeout(function () { $(btn).attr('disabled', 'disabled'); }, 1);
    return true;
});

And I have this input with a javascript confirmation:

<input type="submit" class="click-off" onclick="return confirm('Are you sure?');" value="Delete">

Even if I click "cancel" in the confirmation box, the $('.click-off').click() event is called, and the button becomes disabled.

The $('.click-off').click() is used by a lot of inputs, so the confirmation can't be inside of it.

How can I check the confirm return in the $('.click-off').click event? Or even prevent the $('.click-off').click event to be called?

4

3 回答 3

10

为什么你首先要把这些逻辑分开?以下是解决问题的两种方法:

将逻辑组合成一个方法:

$('.click-off').click(function () {
    // escape here if the confirm is false;
    if (!confirm('Are you sure?')) return false;
    var btn = this;
    setTimeout(function () { $(btn).attr('disabled', 'disabled'); }, 1);
    return true;
});

使用全局变量(或对象最好):

var clickOffConfirmed = false;

<input type="submit" class="click-off" onclick="clickOffConfirmed = confirm('Are you sure?');" value="Delete" />


$('.click-off').click(function () {
    // escape here if the confirm is false;
    if (!clickOffConfirmed) return false;
    var btn = this;
    setTimeout(function () { $(btn).attr('disabled', 'disabled'); }, 1);
    return true;
});
于 2012-12-27T18:00:39.250 回答
2

尝试捕获确认框,然后禁用该按钮。

$('.click-off').click(function () {
  var r=confirm("Press a button");
  if (r==true)
  {
    $(this).attr('disabled', 'disabled');
  }
  else
  {

  }
});

也删除onclick

于 2012-12-27T18:02:15.357 回答
1

您应该避免使用 jquery 和 onclick 挂钩操作,主要是因为很快您将完全迷失在代码中。

因此,例如,您可以这样做:

$('.click-off').click(function () {

   var r=confirm("Are you sure?")
   if (r==true)
   {
       var btn = this;
       setTimeout(function () { $(btn).attr('disabled', 'disabled'); }, 1);
       return true;
   }
   else
   {
       //nothing to do here
   }

});

并删除 onclick 事件。因此,您将把所有东西都放在一个地方。

在您的示例中,您两次连接到 click 事件,尽管结果彼此不同,但它们都会被触发。

于 2012-12-27T18:01:53.843 回答