简体   繁体   English

如何在Javascript中获取同级元素(div)?

[英]How to get sibling element (div) in Javascript?

So I have this HTML: 所以我有这个HTML:

<div class="tip-box">
    <div class="tip-title" onclick="toggleTip()">
        <h2>Tip 1</h2>
    </div>
    <div class="tip-content hidden">
        <p>Tip 1 content</p>
    </div>
</div>

And this Javascript: 而这个JavaScript:

function toggleTip() {
    $(this).siblings(".tip-content").toggleClass("hidden");
}

Hopefully it's obvious what this is supposed to do, but it doesn't work. 希望很明显,这应该做什么,但它不起作用。 Using .siblings() just doesn't seem to work in this way. 使用.siblings()似乎无法以这种方式工作。

What's the correct solution for this? 正确的解决方案是什么? To get the next sibling of a certain type or with a certain class and then hide/show it? 要获取某个类型或某个类的下一个同级,然后隐藏/显示它?

You can use Jquery function. 您可以使用Jquery函数。

<div class="tip-box">
    <div class="tip-title">
        <h2>Tip 1</h2>
    </div>
    <div class="tip-content hidden">
        <p>Tip 1 content</p>
    </div>
</div>

$(document).ready(function(){
    $('.tip-title').click(function(){
        $(this).siblings(".tip-content").toggleClass("hidden");
    });
});

you can also use this 你也可以用这个

<div class="tip-box">
    <div class="tip-title" onclick="toggloTip(this)">
        <h2>Tip 1</h2>
    </div>
    <div class="tip-content hidden">
        <p>Tip 1 content</p>
    </div>
</div>


<script>
function toggloTip(elm) {
    $(elm).siblings(".tip-content").toggleClass("hidden");
}
</script>

How about this JavaScript: 这个JavaScript怎么样:

$(function(){
    $('.tip-box').on('click', '.tip-title', function(){
        $(this).next('.tip-content').toggleClass('hidden');
    });
});

Remove the idea of working with onclick attributes when you use jQuery. 删除使用jQuery时使用onclick属性的想法。

You can use pure javaScript with nextElementSibling property of node something like below, I suppose you want do this operation with siblings. 您可以将纯javaScript与节点的nextElementSibling属性一起使用,如下所示,我想您想对同级对象执行此操作。

 function getChildrens(n, selector) { var nodes = []; while (n.nextElementSibling != null) { if (n.nextElementSibling.hasOwnProperty('classList')) { if (n.nextElementSibling.classList.contains(selector)) { //return n.nextElementSibling; nodes.push(n.nextElementSibling); } } n = n.nextElementSibling; } return nodes; }; function getSiblings(n, selector) { return getChildrens(n, selector); } function toggleTip(elem) { var siblings = getSiblings(elem, "tip-content"); if (siblings.length > 0) { for (var i = 0; i < siblings.length; i++) { siblings[i].classList.toggle("hidden"); } } } 
 .hidden { display: none; } 
 <div class="tip-box"> <div class="tip-title" onclick="toggleTip(this)"> <h2>Tip 1</h2> </div> <div class="tip-content hidden"> <p>Tip 1 content</p> </div> </div> 

None of the previous answers, not even that serial-upvoted one ;), actually explains the problem and why their solutions work. 以前的答案都不对,甚至不是串行upvoted一个),实际上说明了这个问题, 为什么他们的解决方案的工作。

The problem is that an inline onclick handler does not pass on its current context. 问题在于,内联onclick处理程序不会传递其当前上下文。 Inside the onclick="" JavaScript code this is the element clicked. onclick="" JavaScript代码中, this是单击的元素。 Once you call a global function (like your toggleTip ), that context is lost. 一旦调用了全局函数(如您的toggleTip ),该上下文就会丢失。 The this the function receives is window and not the element. this函数接收是window ,而不是元件。

The usual quick fix, for raw JavaScript code, is to pass this as a parameter to the global function. 对于原始JavaScript代码,通常的快速解决方案是将this作为参数传递给全局函数。

eg 例如

onclick="toggleTip(this)" 

and receive a parameter in the function like this: 并在函数中接收如下参数:

function toggleTip(element) {
    $(element).siblings(".tip-content").toggleClass("hidden");
}

However , as you are using jQuery, inline event handlers are actually a bad idea. 但是 ,当您使用jQuery时,内联事件处理程序实际上不是一个好主意。 They separate the event registration from the event handler code for no reason and do not allow for multiple event handlers, of the same type, on the same element. 它们无缘无故地将事件注册与事件处理程序代码分开,并且不允许在同一元素上使用多个相同类型的事件处理程序。 They also bypass the rather cool event bubbling system jQuery uses. 他们还绕过了jQuery使用的相当酷的事件冒泡系统。

The preferred alternative, with jQuery, is to use jQuery to select the element and jQuery to connect the event in one step : 与jQuery相比,首选的替代方法是使用jQuery选择元素,然后使用jQuery 在一个步骤中连接事件:

jQuery(function($){
    $('.tip-title').click(function(){
        $(this).siblings(".tip-content").toggleClass("hidden");
    });
});

As you only want the element that follows, and potentially will add more pairs, the better option would be using nextAll and first() , with the same jQuery filter, instead of siblings : 因为您只想要nextAll的元素,并且可能会添加更多对,所以更好的选择是使用具有相同jQuery过滤器的nextAllfirst() ,而不是siblings

eg 例如

jQuery(function($){
    $('.tip-title').click(function(){
        $(this).nextAll(".tip-content").first().toggleClass("hidden");
    });
});

Or, of you can guarantee it is the next element , use next as @Tim Vermaelen did (with or without the selector makes no difference, so might as well leave it out): 或者,您可以保证它是next元素 ,就像@Tim Vermaelen所做的那样使用next (带有或不带有选择器没有影响,因此不妨将其省略):

jQuery(function($){
    $('.tip-title').click(function(){
        $(this).next().toggleClass("hidden");
    });
});

Note: In this example jQuery(function($){ is a DOM ready event handler which is the rather handy shortcut version of $(document).ready(function(){YOUR CODE}); , which also passes a locally scoped $ value. For those that mistake this code for an incorrect IIFE , here is a working example: http://jsfiddle.net/TrueBlueAussie/az4r27uz/ 注意:在此示例中, jQuery(function($){DOM就绪事件处理程序 ,它是$(document).ready(function(){YOUR CODE});便捷版本,它还传递了本地范围的$对于那些将此代码误认为错误的IIFE的人 ,下面是一个有效的示例: http : //jsfiddle.net/TrueBlueAussie/az4r27uz/

Here is another non JQuery answer. 这是另一个非JQuery答案。

To get the next element sibling use: 要获取下一个元素同级,请使用:

var nextElement = element.nextElementSibling;

To get the previous element sibling use: 要获取先前的元素同级,请使用:

var previousElement = element.previousElementSibling;

To get the element index use: 要获取元素索引,请使用:

var index = Array.prototype.slice.call(element.parentElement.children).indexOf(element);

If you are at the first element the previousElementSibling value will be null. 如果您位于第一个元素,则previousElementSibling值将为null。

If you are at the last element the nextElementSibling value will be null. 如果您位于最后一个元素,则nextElementSibling值将为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM