jquery 如何选取除某个元素外的所有元素?

如题所述

可以使用jQuery 遍历中的 not() 方法来排除某些元素,例如根据元素的id,class等排除,示例代码

$("div.content *").not(".keep"); // 表示content类的div下除keep类以外的所有元素;另外,注意*表示所有元素

下面给出实例演示:删除content类的div下除keep类以外的所有元素

    创建Html元素

    <div class="box">
    <span>点击按钮删除下面绿色框中所有不是keep类的元素,keep类的元素用红色区分。</span><br>
    <div class="content">
    <input type="checkbox" name="item"><span>萝卜</span>
    <input type="checkbox" name="item"><span>青菜</span>
    <input type="checkbox" name="item" class="keep"><span class="keep">小葱</span><br>
    <input type="checkbox" name="item" class="keep"><span class="keep">豆腐</span>
    <input type="checkbox" name="item"><span>土豆</span>
    <input type="checkbox" name="item"><span>茄子</span><br>
    <input type="text" value="我也不是keep类的">
    </div>
    <input type="button" value="删除">
    </div>

    设置css样式

    div.box{width:300px;height:200px;padding:10px 20px;border:4px dashed #ccc;}
    div.box>span{color:#999;font-style:italic;}
    .keep{color:red;}
    div.content{width:250px;height:100px;margin:10px 0;border:1px solid green;}
    input{margin:10px;}
    input[type='button']{width:200px;height:35px;margin:10px;border:2px solid #ebbcbe;}

    编写jquery代码

    $(function(){
    $("input:button").click(function() {
    $("div.content *").not(".keep").each(function() { // "*"表示div.content下的所有元素
    $(this).remove();
    });
    });
    })

    观察显示效果

    删除前

    删除后

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-08-05
有个取巧的方法,让目标盒子消除事件冒泡,给body加个点击事件就行了,不过这种方法适合比较简单的页面,如果交互复杂,多个盒子需要用到消除事件冒泡,这种方法就不那么合适了
$('.targetBox').click(function(e){
// 阻止事件冒泡
if(e.stopPropagation){
e.stopPropagation();
}else{
// 兼容ie
window.event.returnValue == false;
}
})
$('body').click(function(){
console.log('除了加了消除事件冒泡的盒子,触发点击事件')
})
第2个回答  2010-10-14
$("*").not("#demo");//获取除id为demo的所有元素
第3个回答  2010-10-14
eg:
var divs=$("div").not("#div1");//获取除id为div1的所有div本回答被提问者采纳