当试图不包含某些东西时,jquery选择器不起作用

时间:2012-05-18 18:50:55

标签: javascript jquery html jquery-selectors

当我点击tr时,我试图做一个slideToggle,它会扩展一些隐藏的内容。当前,当我这样做时,它会关闭/闪烁,打开和关闭4次。我正在努力做到这一点使得除了div#bounds之外的所有孩子(以及通过关联,它的所有孩子)将获得该onclick属性。

<tr id="attr_expander"><th>Alignment</th><td><input class="attribute" type ="text" disabled="true" />
    <div id="bounds">
       <label><input type="radio" name="toggle" value = "1"><span></span></label>
       <label><input type="radio" name="toggle" value="2"><span></span></label>
       <label><input type="radio" name="toggle" value = "4"><span></span></label><br />
       <label><input type="radio" name="toggle"value = "16"><span></span></label>
       <label><input type="radio" name="toggle"value = "32"><span></span></label>
       <label><input type="radio" name="toggle"value = "64"><span></span></label><br />
       <label><input type="radio" name="toggle"value = "256"><span></span></label>
       <label><input type="radio" name="toggle"value = "512"><span></span></label>
       <label><input type="radio" name="toggle"value = "1024"><span></span></label>
    </div>

jquery是:

$("#attr_expander").find("*:not(div[id='bounds'])").click(function () {
    $("#bounds").slideToggle();
});

让事情变得更好:

#bounds {
    margin:4px;
    background-color:#EFEFEF;
    border-radius:4px;
    border:1px solid #D0D0D0;
    overflow:auto;
    float:left;
}

#bounds label {
    float:left;
    width:2.25em;
    height:3.0em;
    border: 1px solid black;
}

#bounds label span {
    text-align:center;
    padding:3px 0px;
    display:block;

    width:2.25em;
    height:2.75em;
}

#bounds label span:hover
{
    background-color:Aqua;
    border: 1px solid black;
}

#bounds label input {
    position:absolute;
    top:-20px;
}

#bounds input:checked + span {
    background-color:#404040;
    color:#F7F7F7;
}​

3 个答案:

答案 0 :(得分:0)

$("#attr_expander").find('*').not('#bounds, #bounds *').click(function () {
    $("#bounds").slideToggle();
});

Working example

答案 1 :(得分:0)

难道你不能只检查点击事件的目标是什么,只有当节点名是表格单元格时才进行切换吗?

$("#attr_expander").click(function (e) {
    if((e.target.nodeName)=="TH" || (e.target.nodeName)=="TD") $("#bounds").slideToggle();
});​

<强> jsFiddle example

答案 2 :(得分:0)

您可以绑定到该元素,然后检查#bounds是否是父项之一。这样,您只绑定一个事件侦听器,而不是每个元素绑定一个。

http://jsfiddle.net/G3tnQ/3/

$("#attr_expander").on('click', function (e) {
    var bounds = '#bounds',
        $target = $(e.target);

    if (!$target.is(bounds) && $target.closest(bounds).length === 0) {
        $(bounds).slideToggle();
    }
});​