jQuery:不是选择器不能单击

时间:2017-05-06 09:40:59

标签: jquery

以下代码用于在点击#target以外的任何元素但没有效果时,使用“left”和“searchbar”类从li元素中删除“on”类:

$(':not(#target)').click(function() {
$('li.searchbar.left').removeClass("on");
});

这是HTML,基本上如果用户点击任何地方但是#target它将从li中删除on。

<body>
<header></header>
<div class="one"></div>
<div class="two"><a id="target"></a></div>
<ul>
<li class="searchbar left on"></li>
</ul>
<footer></footer>
</body>

3 个答案:

答案 0 :(得分:1)

// if click anywhere on <body> remove class on from given li
$(document).on("click", function() {
    $('li.searchbar.left').removeClass("on");
});

// if click happens on #target do nothing
$('#target').on('click', function(e) {
    e.stopPropagation();
});
body {
  background-color: green;
}

#target {
background-color: powderblue;
width: 100px; height: 100px;
}

li.searchbar.left.on {
  color: orange;
}

li.searchbar.left {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul>
<li class="searchbar left on">hello</li>
</ul>

<div id="target">#target</div>

答案 1 :(得分:0)

对于not选择器,您已将其应用于类似的元素组。

例如,从列表中选择“已选择”类但没有“已选择”类的点击:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div id="div_height" class="form-group has-warning">
    <label for="height" class="col-sm-3 control-label">Hoogte</label>
    <div class="col-sm-9">
        <div class="input-group-btn">
            <span class="input-group-btn">
                <button type="button" class="btn btn-default" id="height_1" name="height" value="1" data-preview="preview_hl_height" onclick="validate_but(this);validate()">14,5</button>
                <button type="button" class="btn btn-default" id="height_2" name="height" value="2" data-preview="preview_hl_height" onclick="validate_but(this);validate()">29,0</button>
                <button type="button" class="btn btn-default" id="height_3" name="height" value="3" data-preview="preview_hl_height" onclick="validate_but(this);validate()">43,5</button>
                <button type="button" class="btn btn-default" id="height_4" name="height" value="4" data-preview="preview_hl_height" onclick="validate_but(this);validate()">58,0</button>
            </span>
            <span class="input-group-addon">cm</span>
        </div>
    </div>
</div>

答案 2 :(得分:-2)

$("body").click(function(ev) {
if(ev.target.id == "target") {
return false;
} else {
// your code
}
})