如何使用1个查询匹配jQuery中的“input”和“select”元素

时间:2010-05-26 04:29:24

标签: javascript jquery jquery-selectors

重,

我有一个简单的查询:

$("#test > fieldset > input").each(function() { })

但是,我想选择“输入”和“选择”元素而不必编写2个“每个”查询。这可能吗?

感谢。

6 个答案:

答案 0 :(得分:3)

$("#test > fieldset").children("input, select")

我们首先找到<fieldset>,然后直接找到所有<input><select>元素。 find的工作方式类似,但会通过树,而不仅仅是直接的孩子。

答案 1 :(得分:2)

jQuery有一些好documentatiion

$("input, select").each(function() { })

答案 2 :(得分:2)

有点冗长的解决方案是:

$("#test > fieldset > input, #test > fieldset > select").each(function() {
  // do stuff
});

或:

$("#test > fieldset > input").add("#test > fieldset > select").each(function() {
  // do stuff
});

:input选择器将匹配超过<input><select>个元素(例如<textarea>)。

答案 3 :(得分:1)

Oy公司!那是documentation

答案 4 :(得分:1)

jQuery提供了一些很好的可扩展性功能。这是一个通用过滤器,可以按多个tag names选择:

/*
 * element: the current element being matched
 * index: index of the current element
 * match: parse tokens from the filter string
 *
 * match[0] -> full filter string
 * match[1] -> filter name
 * match[2] -> ""
 * match[3] -> filter parameter
 */
jQuery.expr[':'].tags = function(element, index, match) {
    var inputs = match[3].split(',');
    var nodeName = element.nodeName.toLowerCase();
    return $.inArray(nodeName, inputs) !== -1;
};​​​​​

它的性能受到影响,因为每个匹配到过滤器点的元素都会调用回调函数,因此我不建议将它用于非常大的文档。

$("#test > fieldset > :tags(input,select)").hide();

答案 5 :(得分:0)

您可以使用

$(document).ready(function(){
$("input, select").each(function() { 
 //do ur stuff
});
});