用jQuery选择多个后代?

Gre*_*reg 15 javascript forms jquery jquery-selectors

我有这样的形式:

<form name="customize">
    Only show results within 
        <select name="distance" id="slct_distance">
            <option>25</option>
            <option>50</option>
            <option>100</option>
            <option value="10000" selected="selected">Any</option>
    </select> miles of zip code
    <input type="text" class="text" name="zip_code" id="txt_zip_code" />
    <span id="customize_validation_msg"></span>
</form>
Run Code Online (Sandbox Code Playgroud)

如何选择inputselect使用一个jQuery选择器?

我尝试了这个,但它选择了页面上的所有选择和输入:

$("form[name='customize'] select,input")
Run Code Online (Sandbox Code Playgroud)

小智 35

选择器字符串中的逗号分隔完全独立的表达式,就像在CSS中一样,因此您给出的选择器获取名为"customize"的表单中的select元素以及表单上的所有输入(如您所述).听起来你想要这样的东西:

$("form[name='customize'] select, form[name='customize'] input")
Run Code Online (Sandbox Code Playgroud)

或者如果你没有重复,这个:

$("form[name='customize']").children("select, input")
Run Code Online (Sandbox Code Playgroud)

  • 或者:$("select,input","form [name = customize]") - 第二个参数是包含元素. (7认同)

vin*_*ent 7

更短的语法$(selector,parentselector)也是可能的.此页面上的示例:

// all spans
$("span").css("background-color","#ff0");

// spans below a post-text class
$("span", ".post-text").css("background-color","#f00");
Run Code Online (Sandbox Code Playgroud)

编辑 - 我忘了几个孩子的特殊情况!

// spans and p's below a post-text class
$("span,p", ".post-text").css("background-color","#f00");
Run Code Online (Sandbox Code Playgroud)