select special selector after $(this) selector

寵の児 提交于 2019-12-17 20:52:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!