【问题标题】:jQuery what instead $(this).parent().children()jQuery 什么代替 $(this).parent().children()
【发布时间】:2011-09-03 13:56:02
【问题描述】:

只是一个简单的例子:

<p>
    <span class="example"></span>
    <input type="text" name="e_name" id="e_id />
</p>
<script type="text/javascript">
    $('input').click(function(){
        $(this).parent().children('span').text('Suprise!');
    }
</script>

我可以用什么代替 parent().children()?

我认为这是一段不雅的代码。 是否有任何功能,即: $(this).fun('span').text('just better'); ??

【问题讨论】:

  • 感谢您提出了一个非常易读的问题,因此我不必点击 3 个不同的答案,不知道里面是什么。

标签: javascript jquery parent children


【解决方案1】:
$(this).siblings('span').text('Suprise!');

【讨论】:

  • 我绝对喜欢.siblings,没想到这个功能,很好的答案。
  • $(this).siblings() 会忽略自己,所以如果你想针对包括自己在内的孩子,parent().children() 仍然很整洁。
【解决方案2】:

试试这个:

$(this).prev('span').text('Surprise!');

【讨论】:

    【解决方案3】:

    稍微优雅一点的是.prev()

    $(this).prev('span').text('Surprise!');
    

    您可以在此处阅读更多信息:Prev

    编辑:向后阅读标记,prev 更好,而不是 next。

    【讨论】:

      【解决方案4】:

      $(this).siblings('span').text('Surprise!');

      在不遍历 DOM 然后返回的情况下将是等效的(我的意思是,它仍然会这样做,但至少你不是手动进行的)。

      【讨论】:

        【解决方案5】:
        $("span.example",$(this).parent()).text('Suprise!');
        

        【讨论】:

          猜你喜欢
          • 2011-05-22
          • 2014-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-15
          • 1970-01-01
          • 2017-11-29
          相关资源
          最近更新 更多