0

这是我的html:

<span class="checkbox checked replacement" tabindex="0">
   <span class="check-knob"></span>
   <input type="checkbox" name="data[InfoPagesClient][3][info_page_id]" value="25"                                                                      checked="checked" class="">
</span>
<label for="InfoPagesClient3InfoPageId" class="label">asdasd</label>

现在我想在复选框单击事件中显示隐藏此铅笔框..

javascript:

$("p.checkbox-group span.checkbox").on('click', function(){
    if($(this).hasClass('checked')) {
        $(imgId).hide();
    } else {
        console.log('aaaaaaaaaaa');
        $(imgId).show();
    }
});

$("label.label").on('click', function(e) {
    if ($(this).siblings('span.checkbox').hasClass('checked')) {
        $(imgId).hide();
    } else {
        $(imgId).show();
    }
    e.stopImmediatePropagation();
});

在标签上单击它将跨越单击事件并打印控制台值...我尝试使用 e.stopPropogation() 和 stopImmediatePropogation().. 但 ti 不工作..

任何想法 ??

4

4 回答 4

0

嗯,这不是一个功能而不是一个错误吗?点击标签不应该触发与点击“复选框”相同的动作吗?for我猜这正是使用该属性的原因。

于 2013-09-11T16:16:27.893 回答
0

e.stopPropogation() 或 e.stopImmediatePropogation() 将防止事件冒泡,但不会立即停止事件。

您可以将 e.preventDefault() 与 e.stopPropogation() 一起使用。e.preventDefault() 将阻止默认事件发生。您可以检查代码中的以下更改。

$("p.checkbox-group span.checkbox").on('click', function(e){
    e.preventDefault();
    e.stopPropagation();

    if($(this).hasClass('checked')) {
        $(imgId).hide();
    } else {
        console.log('aaaaaaaaaaa');
        $(imgId).show();
    }
});

$("label.label").on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();

    if ($(this).siblings('span.checkbox').hasClass('checked')) {
        $(imgId).hide();
    } else {
        $(imgId).show();
    }
});
于 2013-08-10T07:33:34.063 回答
0

当你使用labelwith 时for,浏览器会自动点击触发“点击”事件的关联控件。那是稍后触发的另一个事件,在您使用的情况下e.stopImmediatePropagation();它只是停止当前的“单击”事件,并且对之后触发的关联控件的事件没有影响

要解决您的问题,请尝试删除for

用这个:

<label class="label">asdasd</label>

代替:

<label for="InfoPagesClient3InfoPageId" class="label">asdasd</label>
于 2013-08-10T07:49:16.720 回答
0

如果将id属性添加到复选框,则标签将起作用。然后你可以简化你的代码如下:

$(function () {
    $("p.checkbox-group input[type=checkbox]").on('change', function () {
        if (this.checked) {
            $(this).parent().addClass('checked').siblings('a.edit-content').hide();
        } else {
            $(this).parent().removeClass('checked').siblings('a.edit-content').show();
        }
    });
});

http://jsfiddle.net/gFXcm/2/

于 2013-08-10T07:55:47.517 回答