Jquery 获取下一个兄弟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13922258/
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-26 13:05:35  来源:igfitidea点击:

Jquery get next sibling

jqueryjquery-selectors

提问by Gagan

I am facing some issues while getting elements of the sibling using jquery. I will try to explain.

我在使用 jquery 获取兄弟元素时遇到了一些问题。我会尽力解释。

The following is the HTML that i am currently working on ..

以下是我目前正在处理的 HTML ..

<p class="paraclass1" id="amazing1">
  <span class ="pascal1">
    <div class='pascal'>
        <INPUT id= "chk1" value="on" type="checkbox" />
    </div>
  </span>
</p>
<p>
  <label class='lblclass'>this is a label </>
</p>

what i would like to do is to navigate and find all the children that are present in the second p tag (right now only a label is present) . The following is the Jquery code that i am working on ..

我想要做的是导航并找到出现在第二个 p 标签中的所有孩子(现在只有一个标签)。以下是我正在处理的 Jquery 代码..

$('#chk1').click(function(){
  alert($(this).parents('p#amazing1').next().children().length)

 // alert($('#chk1').parent().parent().attr('class'));
});

http://jsfiddle.net/gj1118/vWQxD/5/

http://jsfiddle.net/gj1118/vWQxD/5/

Any help would be appreciated.

任何帮助,将不胜感激。

Thanks

谢谢

EditI am now trying to get the text of the label that is inside the second p tag element and its not working.... Is there something that I am missing .. ? I havent changed the fiddle yet , but since it was just a sample and since the tags were not being used, i let it remain like it for the sake of simplicity

编辑我现在正在尝试获取第二个 p 标签元素内的标签文本,但它无法正常工作......是否有我遗漏的东西......?我还没有改变小提琴,但因为它只是一个样本,因为没有使用标签,为了简单起见,我让它保持原样

回答by James Allardice

Your jQuery should work fine. The problem in this case is your markup. The pelementcan only contain "phrasing content". The divelement is not classed as phrasing content, so the browser will do its best to handle your markup by moving things around.

您的 jQuery 应该可以正常工作。在这种情况下,问题是您的标记。该p元素只能包含“短语内容”。该div元素不被归类为短语内容,因此浏览器将通过移动内容来尽力处理您的标记。

Chrome simply moves the pelement to become the previous sibling of the div.

Chrome 只需将p元素移动到div.

To fix the issue, you will need to change your markup. Your best bet may be to change the pelement into another div. See an updated fiddle.

要解决此问题,您需要更改标记。您最好的选择可能是将p元素更改为另一个div. 查看更新的小提琴



Side note. You may want to consider changing the .parents()call to a .closest()call. The .parents()method can return multiple elements if they match the selector. In this case that's not possible, but in the interest of maintainability, it could be a good change:

旁注。您可能需要考虑将.parents()呼叫更改为.closest()呼叫。.parents()如果它们与选择器匹配,该方法可以返回多个元素。在这种情况下这是不可能的,但为了可维护性,它可能是一个很好的改变:

$(this).closest('#amazing1').next().children().length