【问题标题】:select special selector after $(this) selector在 $(this) 选择器之后选择特殊选择器
【发布时间】:2015-05-29 06:59:36
【问题描述】:

例如我有这个代码

<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 &gt; div )$( this ' &gt; div ' ) 选择器错误且不起作用

那么你们建议我应该怎么做?

【问题讨论】:

    标签: javascript jquery html jquery-selectors


    【解决方案1】:

    您可以按如下方式使用它:

    $(' > div', $(this))
    

    文档:http://api.jquery.com/child-selector/

    对于直接子元素,可以使用children

    $(this).children('div')
    

    文档:http://api.jquery.com/children/

    使用find

    $(this).find(' > div')
    

    文档:http://api.jquery.com/find/

    Demo

    【讨论】:

      【解决方案2】:

      您可以将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>

      【讨论】:

        猜你喜欢
        • 2011-06-17
        • 1970-01-01
        • 2015-05-09
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        • 2017-12-29
        • 2011-10-26
        • 2017-05-02
        相关资源
        最近更新 更多