【问题标题】:How do I select all inputs except under a specific id?如何选择除特定 ID 下的所有输入?
【发布时间】:2012-08-09 05:32:54
【问题描述】:

我想要做的是选择文档上的所有输入按钮,除了那些驻留在特定 id 下的按钮。

例子:

<body>
<input type="button">

<div id="something">
     <input type="button">
</div>
<div id="something2">
     <input type="button">
</div>


<input type="button">
<input type="button">
<input type="button">
</body>

例如,我想选择所有输入,除了那些位于&lt;div&gt; 下的输入,其id 是“某物”。

我尝试过的:

1) $('input[type="button"]:not(:parent(#something))').addCSS();

2) $('input[type="button"] :not(#something input[type="button"])')

和其他类似的方法

【问题讨论】:

标签: jquery html selector except


【解决方案1】:

你可以这样做(相对有效)。

$("input[type=button]").filter(function() {
    return $(this).closest("#something").length == 0;
});

首先,您获取所有 input[type=button] 元素,然后删除以 #something 为父元素的元素。

另一种可能是这样的:

$("input[type=button]").not("#something input[type=button]")

您必须同时测试两者以查看哪个更有效,但任何一个都可以工作。

两者的工作演示:http://jsfiddle.net/jfriend00/fjxDb/

【讨论】:

    【解决方案2】:

    你就快到了,你需要做的就是删除 :not 之前的空格。

    $('input[type="button"]:not(#something input[type="button"])')
    

    我知道这是一个老问题,但它首先出现在 Google 上,并且在接受的答案中使用 jquery 的 .not() 并不总是一种选择。

    【讨论】:

    • 为什么 jQuery 的 .not() 有时不是一个选项?这是一个 jQuery 问题,所以您可以随时将 .not() 与 jQuery 一起使用,对吗?
    • 当您想动态处理事件时,以及在应用它之后添加的元素上,您通常会使用 $(document).on('theEvent' , '选择器')。在那里,无法将选择器与 .not() 结合使用,但可以在选择器中使用 :not。
    【解决方案3】:

    也许这行得通:$(":not(#something) input[type=button]")

    【讨论】:

    • 我想知道这样做的效率,因为文档中几乎每个对象(除了一个)都会匹配:not(#something)
    • 随便试一试...也许你会有一些运气。下次,如果它已经很容易重建,我建议您自己尝试。
    • 我认为这对性能影响不大;最终的 JQuery 对象被另一个选择器(input[...])减少。无论如何你可以使用div:not(...),但它不会匹配正文中的那些,你必须手动将它们添加到选择器中。
    猜你喜欢
    • 1970-01-01
    • 2022-09-22
    • 1970-01-01
    • 2011-02-02
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    相关资源
    最近更新 更多