问题
for example I have this code
<script>
$(document).ready(function () {
$('span').each(function () {
$(this).html('<div></div>') ;
if ( $(this).attr('id') == 'W0' ) { $( this > div ?!!! ).text('0') }
if ( $(this).attr('id') == 'W1' ) { $( this > div ?!!! ).text('1') }
if ( $(this).attr('id') == 'W2' ) { $( this > div ?!!! ).text('2') }
});
});
</script>
<span id="W0"></span>
<span id="W1"></span>
<span id="W2"></span>
But $( this > div )
or $( this ' > div ' )
are wrong selector & doesn't work
So what do u guys suggest I should do ?
回答1:
You can use it as follow:
$(' > div', $(this))
Docs: http://api.jquery.com/child-selector/
OR
For direct child elements, you can use children
:
$(this).children('div')
Docs: http://api.jquery.com/children/
OR
Using find
$(this).find(' > div')
Docs: http://api.jquery.com/find/
Demo
回答2:
You can pass a context to jQuery along with the selector
$(' > div ', this )
or use children() like
$(this).children('div')
But your solution can be done as
$(document).ready(function() {
var texts = {
W0: '0',
W1: '1',
W2: '2'
}
$('span').each(function() {
$('<div />', {
text: texts[this.id]
}).appendTo(this)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="W0"></span>
<span id="W1"></span>
<span id="W2"></span>
来源:https://stackoverflow.com/questions/30523117/select-special-selector-after-this-selector