select special selector after $(this) selector

2019-01-20 12:59发布

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 ?

2条回答
祖国的老花朵
2楼-- · 2019-01-20 13:37

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>

查看更多
够拽才男人
3楼-- · 2019-01-20 13:42

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

查看更多
登录 后发表回答