Dan*_* Na 3 html javascript jquery jquery-selectors
例如,我有这个代码
<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>
Run Code Online (Sandbox Code Playgroud)
但$( this > div )还是$( this ' > div ' )有错的选择与不工作
那么你们有什么建议我应该做什么?
您可以按如下方式使用它:
$(' > div', $(this))
Run Code Online (Sandbox Code Playgroud)
文档:http://api.jquery.com/child-selector/
要么
对于直接子元素,您可以使用children:
$(this).children('div')
Run Code Online (Sandbox Code Playgroud)
文件:http://api.jquery.com/children/
要么
运用 find
$(this).find(' > div')
Run Code Online (Sandbox Code Playgroud)
文档:http://api.jquery.com/find/
$(' > div ', this )
Run Code Online (Sandbox Code Playgroud)
或者使用children()之类的
$(this).children('div')
Run Code Online (Sandbox Code Playgroud)
但您的解决方案可以完成
$(document).ready(function() {
var texts = {
W0: '0',
W1: '1',
W2: '2'
}
$('span').each(function() {
$('<div />', {
text: texts[this.id]
}).appendTo(this)
});
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)