开发者

How is multiple selection working in this example?

The relevant snippet of HTML:

<span class="a">
<div class="fieldname">Qu开发者_JAVA技巧estion 1</div>
<input type="text" value="" name="q1" />
</span>

The relevant jQuery:

$.each($('.a'), function(){
$thisField = $('.fieldname', $(this));
});

What exactly is being set to $thisField? If my understanding of multiple selectors in jQuery is correct, it should be grabbing the outer <span> element AND the inner <div> element. But for some reason, if I use $thisField.prepend("hi"); it ends up putting hi right before the text Question 1, but not before <div>. I thought multiple selectors would grab both elements, and that prepend() adds hi to the beginning of BOTH elements, not just the <div>


The calling convention you are using is not a "multiple-selector" it is in fact searching within the context ($(this)) for a selector ('.fieldname'). See docs.

You could do this to get the <div> and the <span>:

$(this).find('.fieldname').andSelf().prepend('hi');


$('.fieldname', $(this)); is equivalent to $(this).find('.fieldname');

don't get this confused with something like: $('.class1, class2');.

$('.class1, class2'); has only one parameter inputted.


"The .prepend() method inserts the specified content as the first child of each element in the jQuery collection" http://api.jquery.com/prepend/

Since you're targeting all elements with class "fieldname" within an element that has "a" class the output is right.


But for some reason, if I use $thisField.prepend("hi"); it ends up putting hi right before the text Question 1, but not before <div>.

Did you try this?

$.each($('.a'), function(){
  $('hi').insertBefore($('.fieldname', $(this)));
});


I'm not sure what you mean with multiple selectors, cause what I see you're doing is just selecting the <div class="fieldname">. All .prepend is doing is adding hi before the content of that div.

So here you're not selecting more than one element.


Multiple selectors work inside the selector string..

like this

$multiple= $('.fieldname, a'); 
// this will select all <a> elements and all elements with class 'fieldname'


$.each($('.a')

means "for each element that has class=a" (in this case, only your span), so if your div also had class=a then you would see the outcome you expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜