单击时如何使禁用按钮执行某些操作? (JS)

时间:2013-12-19 16:02:34

标签: javascript jquery button

所以我有这段代码:

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>";

它检查是否符合某个标准,如果是,则禁用按钮但是一旦按钮被禁用,我想在点击它时仍然会发生什么事情?我已经尝试了我能想到的一切,并希望得到一些建议。 在此先感谢:)

2 个答案:

答案 0 :(得分:2)

或者,当单击禁用按钮时实际触发事件时,可以在禁用按钮前添加虚拟元素,并在该元素上添加与禁用状态关联的侦听器。例如,

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>

答案 1 :(得分:1)

使用以下代码

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