jQuery代替$(this).parent().children()

Mr *_*oul 19 javascript jquery children parent

只是一个简单的例子:

<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>
Run Code Online (Sandbox Code Playgroud)

我可以使用什么而不是parent().children()?

我认为这是一段有点不优雅的代码.是任何函数,即:$(this).fun('span').text('just better'); ??

Chr*_*ong 48

$(this).siblings('span').text('Suprise!');
Run Code Online (Sandbox Code Playgroud)

  • `$(this).siblings()`会忽略它自己,所以如果你想要包括它自己的子项,`parent().children()`仍然很整洁. (2认同)

roc*_*est 7

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

如果没有遍历DOM然后退回(我的意思是,它仍然会这样做,但至少你不是手动完成).