【问题标题】:How can I make a disabled button do something when clicked? (JS) [duplicate]单击时如何使禁用的按钮执行某些操作? (JS)[重复]
【发布时间】:2013-12-19 16:02:33
【问题描述】:

所以我有这段代码:

var delete_disabled = (parseInt(row.attr("data-state"), 10) === serverVars.obligationStateNotStarted) ? '' : 'disabled="disabled"';
        newHtml += "<button class=\"delete small\"" + delete_disabled + " title=\"" + labelDelete + "\"><i class=\"icon-trash\"></i></button>";

它检查是否满足某个条件,如果满足则禁用该按钮,但是一旦禁用该按钮,我希望单击它时仍会发生某些事情吗?我已经尝试了我能想到的一切,并希望得到一些建议。 在此先感谢:)

【问题讨论】:

  • 使用它的布局来给人一种它被禁用的印象,但不要禁用它,只需为点击事件附加一个不同的处理程序。
  • 不要禁用它,让它看起来像被禁用(从用户的角度来看,灰色文本和背景等)并用变量或其他东西处理它的状态。
  • 这不是禁用按钮,而是通过替换/重新解析它的 HTML 来破坏它,以便拥有一个带有(甚至不是标准的)禁用键盘的全新且不同的按钮。使用属性disabled="disabled"
  • 禁用一个按钮并假装它在禁用时仍然做某事是一个很大的“不”恕我直言。

标签: javascript jquery button


【解决方案1】:

除了在单击禁用按钮时实际触发事件之外,您还可以在禁用按钮前添加一个虚拟元素,并在该元素上添加与禁用状态相关联的侦听器。例如,

http://jsfiddle.net/FN45M/

js

$(document).ready(function () {
/*this click listener could also be added as part of the disableButton function.*/
    $(document).on('click', '.click-div', function () {
        console.log('clicked');
        alert('clicked');
    });

    disableButton($('button'));
    //enableButton($('button'));

});

function disableButton($el){
    var wrapper = $el.wrap("<div class='wrapper'>").parent();
    wrapper.css({"display":"inline","position":"relative"});
    var divClick = $("<div class='click-div'>");
    divClick.css({"position":"absolute",
                  "top":0,
                  "height":"100%",
                  "width":"100%"
                 });
    wrapper.append(divClick);

    /*divClick.on('click', function () {
        console.log('clicked');
        alert('clicked');
    });*/
}

function enableButton($el){
    $el.next(".click-div").remove();
    $el.unwrap("<div class='wrapper'>");
    $el.prop("disabled",false);
}

html

<button disabled>test</button>

【讨论】:

    【解决方案2】:

    使用以下代码

    jQuery:

    $("button#disabled, button#enabled").click(function(){
        if($(this).attr('id') === 'disabled'){
            alert('disabled');
            // do your suff here for disabled button
        } else {
            alert('enabled');
            // do your suff here for enabled button
        }
    });
    

    HTML:

    <button id="disabled" style="color: graytext;"><i>disabled</button>
    <button id="enabled">enabled</button>
    

    Example here

    【讨论】:

      猜你喜欢
      • 2012-11-15
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多