Javascript jQuery 取而代之的是 $(this).parent().children()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6155638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:28:10  来源:igfitidea点击:

jQuery what instead $(this).parent().children()

javascriptjqueryparentchildren

提问by Mr Sooul

Just a quick example:

只是一个简单的例子:

<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>

What can I use instead parent().children()?

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

I think it's a bit inelegant piece of code. Is any function i.e : $(this).fun('span').text('just better'); ??

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

回答by Christopher Armstrong

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

回答by rockerest

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

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

Would be the equivalent without traversing up the DOM and then back down (I mean, it still does it, but at least you're not doing it manually).

无需遍历 DOM 然后返回即可等效(我的意思是,它仍然会这样做,但至少您没有手动进行)。

回答by Jeremy B.

Slightly more elegant is .prev()

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

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

you can read more about it here: Prev

你可以在这里阅读更多关于它的信息:上一页

edit: read the markup backwards, prev is better, not next.

编辑:向后阅读标记,上一个更好,而不是下一个。

回答by Ryan Olds

$("span.example",$(this).parent()).text('Suprise!');

回答by drudge

try this:

尝试这个:

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