混淆获取类名来隐藏链接

时间:2018-01-04 09:38:01

标签: javascript jquery html

我有这个代码,可以通过点击第一个元素来显示/隐藏第二个元素:

<script>
var acc = document.getElementsByClassName("movs-header");
var i;
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        var x = this.nextElementSibling;
        if (x.style.display === "block") {
            x.style.display = "none";
        } else {
            x.style.display = "block";
        }
    }
}
</script>

这是结构(它们是php系统中的重复元素):

<div id="frm_container_[id]" class="movs-box">
    <div class="movs-header">
        some content here, clickable to show-hide the next sibling div
    </div>
    <div class="movs-body">
        this content will show and hide
    </div>
</div>

现在,我需要在div中添加一个带有class =“movs-editlink”的链接,它必须在movs-box div之外才能引用id“frm_container”,以便工作。

然后结构将是:

<div id="frm_container_[id]" class="movs-box">
    <div class="movs-header">
        some content here, clickable to show-hide the next sibling div
    </div>
    <div class="movs-body">
        this content will show and hide
    </div>
</div>
<div class="movs-editlink">[editlink label="edit" prefix="frm_container_"]</div> <!-- this div to show and hide along -->

(请不要介意短代码,它可以正常工作)

我需要的是用相同的javascript代码显示/隐藏最后一个div(当我点击“movs-header”div时,但我没有引用“this.className”,我的猜测是:

<script>
var acc = document.getElementsByClassName("movs-header");
var i;
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        var x = this.nextElementSibling;
        var xedit = this.getElementsByClassName("movs-editlink").classname;
        if (x.style.display === "block") {
            x.style.display = "none";
            xedit.style.display = "none";
        } else {
            x.style.display = "block";
            xedit.style.display = "block";
        }
    }
}
</script>

我认为这不起作用,因为最后一个div超出了“this”的范围,那么我想我需要在结构中找到NEXT div,并将类“movs-link”包含在显示切换中, 我对吗?但我找不到怎么样。请帮忙。

1 个答案:

答案 0 :(得分:0)

根据您的标记而不是getElementsByClassName的{​​{1}},使用this

进行
this.parentNode.nextElementSibling

或者使用jquery&#39; nextUntil

var xedit = this.parentNode.nextElementSibling;