javascript 迭代每个兄弟元素

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

Iterate over each sibling element

javascriptjqueryclassselector

提问by Joel G Mathew

Context:I'm building a form and script which will perform an ajax query, based on clicking a specific button. There are multiple div blocks with elements of the same class, and based on the div block in which, a button is clicked, different forms will be processed.

上下文:我正在构建一个表单和脚本,它将基于单击特定按钮执行 ajax 查询。有多个具有相同类元素的div块,并基于其中的div块,点击一个按钮,将处理不同的表单。

As part of beginning the program, I have started with an apparently simple jQuery call.

作为开始程序的一部分,我从一个看似简单的 jQuery 调用开始。

I'm trying to add an onclick event to a specific class, and then trying to get the CSS value of the siblings of that element.

我正在尝试向特定类添加 onclick 事件,然后尝试获取该元素的兄弟元素的 CSS 值。

Error:I'm getting an error stating that TypeError: this.siblings is undefined.

错误:我收到一个错误,指出TypeError: this.siblings is undefined.

Question:What is the proper way to iterate over siblings of an element using jQuery?

问题:使用 jQuery 迭代元素的兄弟元素的正确方法是什么?

My code:

我的代码:

HTML:

HTML:

<a class="btn LiveStatsBtn"><span class="btn-label">Get Stats now</span> </a>

JavaScript:

JavaScript:

$(document).ready (function()
{ 
    $('.LiveStatsBtn').click(function(){
        this.siblings.each( function () {
            var tx=this.css();
            alert(tx);
        });
    });
});

回答by Pointy

In a jQuery event handler, thisrefers to the DOM element, and is not a jQuery object. You have to wrap it in one:

在 jQuery 事件处理程序中,this指的是 DOM 元素,而不是 jQuery 对象。你必须把它包装成一个:

$(this).siblings().each(function() {
  // ...
});

Also note that "siblings" is a function, so you have to call it to get a new jQuery object that wraps the element siblings.

还要注意,“siblings”是一个函数,所以你必须调用它来获取一个新的 jQuery 对象来包装元素兄弟元素。

回答by Nicklas Nygren

siblingsis a function, so it needs parentheses:

siblings是一个函数,所以它需要括号:

$(document).ready (function()
{ 
    $('.LiveStatsBtn').click(function(){
        $(this).siblings().each( function () {
            var tx=$(this).css();
            alert(tx);
        });
    });
}); 

http://api.jquery.com/siblings/

http://api.jquery.com/siblings/