简体   繁体   中英

jQuery selector problem

<input type="radio" id="rad1" name="group" value="one">First Option</input><br>
<input type="radio" id="rad2" name="group" value="two">Second Option</input><br>
<input type="radio" id="rad3" name="group" value="three">Third Option</input><br>

<br>

<input type="radio" id="rad7" name="group2" value="one">First Option</input><br>
<input type="radio" id="rad8" name="group2" value="two">Second Option</input><br>
<input type="radio" id="rad9" name="group2" value="three">Third Option</input><br>

The following statements are true

$('[value="one"]').length == 2

$('[name="group2"]').length == 3

So how come..

$('[value="one"]',$('[name="group2"]')).length == 0

?

I would have thought that this should effectively look within all elements with name==group2 for elements with value=="one" ie 1 . Why is this not the case?

This selector, using the second argument for scope/context:

$('[value="one"]', $('[name="group2"]'))

Attempts to find elements with [value="one"] that descend from elements with [name="group2"] . That means you end up looking down at least two levels of different elements in the DOM.

In your case, your radio buttons have both attributes, so you want to attach both attribute selectors instead (I add input just to save jQuery some work):

$('input[name="group2"][value="one"]')

I think what you want is:

$('[name="group2"][value="one"]')

This selects elements that have a name attribute with value group2 and value attribute with value one .

$(selector, element) is something different. It will find all descendants of element which match selector . See the documentation .

$('input:[value="one"], input:[name="group2"]').length === 5

You have to use one string, comma separated. BTW it's bad practice to write a selector like [anything=foobar] . That is an implicit usage of the universal selector(*) which would query all elements in your markup.

This would query both selectors and add the results together in a wrapped set. If you want query for nodes which own both attributes, wire things up like:

$('input:[value="one"][name="group2"]').length === 1

You want this instead to find value one from group2 :

$('input[name="group2"][value="one"]').length

This is called the multiple-attribute-selector (docs) .

Notice that I also added an input tag selector. This is so every element on the page doesn't need to be analyzed.

尝试$('[value =“ one”],[name =“ group2”]')的长度

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM