如何在禁用的元素上触发单击事件

use*_*490 6 javascript jquery

我有一个禁用按钮,在选中"我接受条款和条件"复选框后启用.问题是,如果用户单击禁用按钮,我想触发警报.我怎样才能做到这一点?如果某个元素被禁用,则看起来"onclick"事件不会被触发.

代码示例:

<input id="subm_tc" class="btn btn-primary" type="submit" disabled="" value="Log in" name="Submit">

    $("#subm_tc").click(function () {
        if($("#modlgn-tc").is(':checked')){
            alert('checked');
        } else {
            alert('unchecked');
        }
    });
Run Code Online (Sandbox Code Playgroud)

如果我将该元素包装在div中并听取对该div的点击,则它可以正常工作,但您需要在按钮外单击.

我怎样才能解决这个问题?

谢谢

UPDATE.我设法通过在提交按钮上添加一个假div并在该div上侦听事件来解决这个问题(我还将z-index更改为-200以启用对按钮本身的点击):

<div style="position:relative">
<div id="subm_tc" style="position: absolute; left: 0px; right: 0px; bottom: 0px; top: 0px; z-index: 99999;"></div>
<input id="subm_tc" class="btn btn-primary" type="submit" disabled="" value="Log in" name="Submit">
</div>
Run Code Online (Sandbox Code Playgroud)

现在它按预期工作

chi*_*NUT 6

我的解决方案是将按钮放在div中,这是可单击的。当禁用按钮时,div具有按钮的宽度和高度,因此单击按钮将触发div。启用按钮后,div缩小为0宽度0高度,因此click事件向按钮而不是div注册。该代码还包括用于切换按钮的一些演示代码,该切换按钮可切换相关按钮的启用/禁用状态

小提琴:http//jsfiddle.net/6as8b/2/

的HTML

单击“切换”以启用或禁用“按钮”。单击它,可以看到如果启用了则触发一个事件,如果禁用则触发另一个事件。

<input type=button value='toggle' id='toggle'><BR>
<div style='position:relative'>
    <div id='clickable'></div>
    <input id=theButton type=button disabled value='Button'>
        </div>
    <div id=clicks></div>
Run Code Online (Sandbox Code Playgroud)

的CSS

#clickable{
position:absolute;
    width:55px;
    height:25px;
}
Run Code Online (Sandbox Code Playgroud)

JS

$(document).ready(function () {
    $('#clickable').on('click',function () {
        if ($('#theButton:disabled').length>0)
        {
        $('#clicks').append('|Disabled Button Clicked|<br>');
        }
        else
        {
            //do nothing and let the button handler do it
            $('#theButton').click();
        }
    });
    $('#theButton').on('click',function() {
        $('#clicks').append('|ENABLED button clicked|<br>');
    });
        $('#toggle').on('click',function() {
       if ($('#theButton:disabled').length>0)
        {
            $('#theButton').removeAttr('disabled');
            $('#clickable').css({'width':'0px','height':'0px'});
        }
            else
            {
                $('#theButton').attr('disabled','disabled');
                $('#clickable').css({'width':'55px','height':'25px'});
            }
    });
});
Run Code Online (Sandbox Code Playgroud)