jquery - 使用 :not(these) 禁用表单中的所有输入

jquery - disable all inputs in form with :not(these)

不确定这是否可行,或者我只是写得不正确:

}).on("change", function (e) {
    $("#searchForm:not('#locationName') :input").prop("disabled", true);
});

#searchForm是整个表单的id

#locationName 是我要排除的特定输入的 id(不止这个,但这是一个例子)

我想排除多个输入 ID,并在表单中列出大量输入 ID,因此我不想逐一禁用...我想使用 not() 选择器如果可能的话。

我已经尝试了几种不同的方式来编写它,但似乎无法正常工作。

#searchForm is the id of the entire form

#locationName is the id of a particular input I would like to exclude

在这种情况下,:not 应该在 :input 上,而不是 #searchForm:

.on("change", function (e) {
  $("#searchForm :input:not('#locationName')").prop("disabled", true);
});

您当前的代码在 #searchForm 元素中查找输入,该元素也不是 #locationName 元素。由于一个元素只能有一个 ID,所以没有意义。您将 :not 应用于错误的元素。

您打算将 :not 放在 :input 伪 class 上。

$("#searchForm :input:not(#locationName)").prop("disabled", true);

另请注意,您不需要在 :not.

中的选择器周围加上引号

如果您有多个元素要排除,请记住,当您构建复合选择器时,它们是通过 AND 连接在一起的,因此请使用多个 :nots:

$("#searchForm :input:not(#locationName):not(#somethingElse)").prop("disabled", true);

实际上,话虽如此,我从 the jQuery documentation 看到他们扩展了 :not 以允许组选择器:

// Only valid with jQuery
$("#searchForm :input:not(#locationName, #somethingElse)").prop("disabled", true);

那是 not valid in CSS which only allows simple selectors,它是 jQuery 的扩展名(就像 :input 一样)。通过使用 jQuery 扩展,您可以强制 jQuery 使用其 Sizzle 引擎处理选择器本身,而不是将其交给浏览器——效率更高的内置引擎,但在大多数情况下速度不同没关系。

或者,您可以使用 .not function:

// Only valid with jQuery
$("#searchForm :input").not("#locationName, #somethingElse").prop("disabled", true);