2015-05-29 122 views
3

例如我有这样的代码选择特殊的选择

<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> 

$(this > div)$(this ' > div ')是错误的选择&不起作用

那么什么ü人建议我应该做的?

回答

6

您可以选择一起传递context to jQuery

$(' > div ', this) 

或使用children()

$(this).children('div') 

但您的解决方案可以做到

$(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>