Jquery第一次出现树遍历父母/兄弟姐妹

发布于 2024-10-17 10:09:23 字数 668 浏览 0 评论 0原文

给定一个类最接近(树上)的最佳方法是什么,但它可以是父级的兄弟姐妹。

我想让“errors1”元素以元素“.start”开头

<div>
    ...
    <div class="errors">errors2</div>
    <div>
        .....
        <div class="errors">errors1</div>
        ...
        <div>...</div>
        <div>
            .....
            <div class="start"></div>            
        </div>     
    </div>
</div>

制作了一个脚本,但它真的很糟糕并且根本不起作用。

http://jsfiddle.net/9DfCJ/1/

谢谢

编辑: 添加“...”以增强结构的动态性。重点是找到树上最接近的“.errors”。

What is the best way to get closest (up tree) given a class, but it can be a sibling of a parent.

I want to get "errors1" element start with element ".start"

<div>
    ...
    <div class="errors">errors2</div>
    <div>
        .....
        <div class="errors">errors1</div>
        ...
        <div>...</div>
        <div>
            .....
            <div class="start"></div>            
        </div>     
    </div>
</div>

Made a script but its really bad and doesnt work at all.

http://jsfiddle.net/9DfCJ/1/

Thanks

EDITED:
Added "..." to enhance that structure is dynamic. The point is to find the closest ".errors" up tree.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

耳钉梦 2024-10-24 10:09:23

很好的问题。下面的代码应该适合你。它循环遍历 .start 的每个父元素,直到找到带有 .errors 的元素。然后,它会警告最接近 .start.errors 元素的文本。

jQuery(function($){

    var $start = $('.start'),
        $parents = $start.parents();

    $parents.each(function(){
        var $this = $(this),
            $thisErrors = $this.find('.errors'),
            numErrors = $thisErrors.length;

        if(numErrors){
            alert($thisErrors.eq(numErrors-1).text());
            return false;
        }

    });

});

Great question. The code below should work for you. It loops over each parent of .start until it finds an element with .errors. Then it alerts the text of the .errors element that is closest to .start.

jQuery(function($){

    var $start = $('.start'),
        $parents = $start.parents();

    $parents.each(function(){
        var $this = $(this),
            $thisErrors = $this.find('.errors'),
            numErrors = $thisErrors.length;

        if(numErrors){
            alert($thisErrors.eq(numErrors-1).text());
            return false;
        }

    });

});
尬尬 2024-10-24 10:09:23
$(this).parent().siblings(':first')
$(this).parent().siblings(':first')
只有一腔孤勇 2024-10-24 10:09:23

研究 jQuery 的 prev() 命令。例如,要在“start”类的上下文中查找并隐藏以前的“错误”,您可以使用以下内容:

$('.start').click(function(){
  $(this).prev('.errors').hide();
});

在此处阅读更多信息:http://api.jquery.com/prev/

更新:

使用 parent() 进行遍历可能会有更好的运气如果嵌套很重,则向上。 parent() 还接受一个选择器作为参数...如果没有参数,它会获取当前节点的父节点。

http://api.jquery.com/parent/

Investigate jQuery's prev() command. For example, to find and hide the previous 'errors' when in the context of the 'start' class, you would use the following:

$('.start').click(function(){
  $(this).prev('.errors').hide();
});

Read more here: http://api.jquery.com/prev/

UPDATE:

You may have better luck using parent() to traverse upward if it is heavily nested. parent() also takes a selector as an argument... without an argument it grabs the parent of the current node.

http://api.jquery.com/parent/

挽手叙旧 2024-10-24 10:09:23

一个将项目作为 jQuery 对象返回的函数,因此它更可重用。

这比 Byran 的答案更有效,因为它一次只查看一个级别,而不是加载所有父级并通过 find (http://api.jquery.com/find/) 每次。

要使用该函数,只需在加载 jQuery 后将该函数粘贴到 javascript 文件或脚本标记中即可。

$('.start').closestParentsAndSibling( '.errors').html('found!');

(function( $ ){
   $.fn.closestParentsAndSibling = function(search) {
        // Get the current element's siblings
        var siblings = this.siblings(search);

        if (siblings.length != 0) { // Did we get a hit?
            return siblings.eq(0);
        }

        // Traverse up another level
        var parent = this.parent();
        if (parent === undefined || parent.get(0).tagName.toLowerCase() == 'body') {
            // We reached the body tag or failed to get a parent with no result.
            // Return the empty siblings tag so as to return an empty jQuery object.
            return siblings;
        }
        // Try again
        return parent.closestParentsAndSibling(search);
   }; 
})( jQuery );

A function to return the item as a jQuery object so it is more reusable.

This is more efficient than Byran's answer because it only looks at one level at a time rather than loading all parents and checking all levels of children via find (http://api.jquery.com/find/) each time.

To use, just paste the function into your javascript file or script tags after jQuery has been loaded.

$('.start').closestParentsAndSibling( '.errors').html('found!');

(function( $ ){
   $.fn.closestParentsAndSibling = function(search) {
        // Get the current element's siblings
        var siblings = this.siblings(search);

        if (siblings.length != 0) { // Did we get a hit?
            return siblings.eq(0);
        }

        // Traverse up another level
        var parent = this.parent();
        if (parent === undefined || parent.get(0).tagName.toLowerCase() == 'body') {
            // We reached the body tag or failed to get a parent with no result.
            // Return the empty siblings tag so as to return an empty jQuery object.
            return siblings;
        }
        // Try again
        return parent.closestParentsAndSibling(search);
   }; 
})( jQuery );
终陌 2024-10-24 10:09:23

如果你想在树上查找所有错误,你可以这样做:

var start = $(".start"),
    current = start.parent(),
    parent = current,
    end_class = "stop",
    get_errors = function(elt) {
        return elt.children(".errors");
    },
    errors = get_errors(current)

    while (parent = current.parent()) {

        $.merge(errors, get_errors(parent));
        if (parent.hasClass(end_class)) {
           break;
        }   
        current = parent;
    }

最后,errors 将包含所有错误。

不过,您必须将 end_class 添加到您的顶部 div 中。

<div class="stop">
    ...
    <div class="errors">errors2</div>
    ...
</div>

If you want to go up the tree, and get all the errors, you could do something like that:

var start = $(".start"),
    current = start.parent(),
    parent = current,
    end_class = "stop",
    get_errors = function(elt) {
        return elt.children(".errors");
    },
    errors = get_errors(current)

    while (parent = current.parent()) {

        $.merge(errors, get_errors(parent));
        if (parent.hasClass(end_class)) {
           break;
        }   
        current = parent;
    }

At the end, errors will contain all the errors.

You would have to add the end_class to your top div though.

<div class="stop">
    ...
    <div class="errors">errors2</div>
    ...
</div>
江湖正好 2024-10-24 10:09:23

我做了一些挖掘,发现了一些东西可以获取与选择器匹配的第一个元素,从当前元素开始并向上推进:

var myText = $(".start").closest($(".errors")).text(); 

阅读有关它的更多信息 此处,您可以使用您的事件来调用此代码。

I did some digging and found something to get the first element that that matches the selector, beginning at the current element and progressing up :

var myText = $(".start").closest($(".errors")).text(); 

read more about it here and you can use your event to call this code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文