jquery:即使按钮被禁用,也会调用click回调?

时间:2012-02-04 21:53:22

标签: jquery button click

我有这段代码:

// jquery
$(':button').live('click', eventHandler);

<!--html-->
<button type="button" name="lvldown" disabled="disabled">Level down</button>

我预计,如果因为w3schools上的<button> disabled description按钮被禁用,则点击后不会调用点击事件:

  

定义和用法

     

disabled属性指定应禁用按钮。

     

禁用按钮无法使用且无法点击。

但是,点击后我的eventHandler仍在调用。这是为什么?我真的需要做$(':button:not([disabled])').live('click', eventHandler);之类的事情吗?

编辑:问题实际上仅在我的Chrome 16.0.912.77下出现问题。在Firefox和IE下我的代码工作正常。顺便说一句。我使用jquery 1.7.1。以下是一些截图: the buttonconsole after loadconsole after click on the button

我的代码现在基本上是这样的:

jQuery(document).ready(function() {
    $(':button').live('click', eventHandler);
    constraintActions();
});

function constraintActions() {
    // level down
    $('.shopCat').not('.shopCat[data-parent]').each(function() {
        var lvlDownButton = $(this).children('p').children('[name=lvldown]');

        if ($(this).children('.shopCat').size() > 0 || 
                $(this).next('.shopCat').size() == 0) {
            lvlDownButton.addClass('disabled'); 
            lvlDownButton.attr('disabled', 'disabled'); // also tried: lvlDownButton.prop("disabled", true);
        } else {
            lvlDownButton.removeClass('disabled');  
            lvlDownButton.removeAttr('disabled'); //also tried: lvlDownButton.prop("disabled", false);
        }
    });

function eventHandler() {
    console.log($(this));
}

EDIT2:实际上按钮html如下所示:

<button type="button" class="submit btn-generic" name="lvldown" disabled="disabled">
    <span class="lvldown">Podřadit</span>
</button>

我试图保持一个本质,但似乎我遗漏了一些重要的东西,重要的是内部的跨度因为以下工作(!)如预期的那样:

<button type="button" class="submit btn-generic" name="lvldown" disabled="disabled">
    Podřadit
</button>

如果我尝试在评论中提供的示例中添加内部跨度,我会得到这些结果(在chrome 16.0.912.77下):

Javascript(by j08691):

$('button').live('click', function(){alert('FIRE!')});

Html(j08691):

<button type="button" disabled="disabled">Level down</button> <!-- does not fire -->
<button type="button" disabled="disabled"><span>Level down</span></button> <!-- does fire!-->

Javascript(由Pointy提供,jquery设置为1.5.2版):

$<button disabled>Hi</button>('button').live('click', function() {
    alert("click");
});

Html(由Pointy提供):

<button disabled>Hi</button> <!-- does not fire -->
<button disabled><span>Hi</span></button> <!-- does not fire -->
<!-- after changing jquery version to 1.7.1 -->
<button disabled><span>Hi</span></button> <!-- does fire! -->

在Firefox下,它无论如何都不会触发,只是在(我的)chrome下它的行为就像这样。我在做什么有什么不对吗?

P.S。抱歉我的帖子已经变得很长了

2 个答案:

答案 0 :(得分:0)

我发现这是jQuery的问题&lt; 1.5和IE(至少IE8)。在IE8中尝试one of the working examples above,然后从左侧的下拉列表中选择jQuery 1.4.4。 要解决此问题,请尝试更新jQuery库。

答案 1 :(得分:0)

理想情况下,标记内不应包含任何HTML标记,异常是应该避免使用的标记,并使用CSS来获得相同的效果。

如果您使用它来保存类属性,则应将此应用于按钮本身,因为应用于按钮的任何格式都将应用于按钮内容,包括文本。

从您的问题中可以明显看出,您的问题源于内部,因此尝试将其删除并将类应用于实际按钮。