繁体   English   中英

有人可以解释此功能的工作原理吗?

[英]Can someone explain how this function is working?

因此,我正在做的是创建一个网站,当您单击按钮时,该网站显示有关某个人的信息。 该信息显示在页面一部分上的文本框中,您可以单击人员姓名旁边的“信息”按钮以使内容显示在文本框中。 我遇到的问题是,当我单击第二个“信息”按钮以显示其他人的信息时,我无法使内容消失。 我了解必须创建一个函数来将“显示”属性从“无”更改为“阻止”。 我了解该函数的前两个语句,但是一旦到达“ if ... return”语句,我将不知道发生了什么。 任何帮助解释这一点都将非常棒!

谢谢!

function resetBioVisi()
{
    var bioElem = document.getElementById("bio");
    var bios = bioElem.childNodes;
    if (bios.length == 0) return;
    for (var index = 0; index < bios.length; index++)
        if (bios[index].style !== undefined)
                bios[index].style.display="none";
}
function resetBioVisi()
{
    //get bio element by id
    var bioElem = document.getElementById("bio");

    //get all child elements of bios
    var bios = bioElem.childNodes;

     //if there are no child elements, do nothing (exit function)
    if (bios.length == 0) return;

     //otherwise, for each element in the list of bios's child elements...
    for (var index = 0; index < bios.length; index++)

        //if the element has a style
        if (bios[index].style !== undefined)

                //set that style to none (make it hidden)
                bios[index].style.display="none";
}

function resetBioVisi()是函数声明。 这是函数名称和任何参数。

var bioElem = document.getElementById("bio"); 从dom获取ID为“ bio”的元素。

var bios = bioElem.childNodes; 获取bioElem的所有子节点。

if (bios.length == 0) return; 如果bioElem没有孩子,请立即离开该功能,不要继续。 在这种情况下,for循环不会运行。

for (var index = 0; index < bios.length; index++)这是一个循环。 您定义了一个索引变量(在本例中为index ),一个停止条件和一个迭代器。 这是“对bioElem所有孩子执行以下操作。

if (bios[index].style !== undefined)检查当前子节点的样式。 如果未定义,请输入块。 如果已定义,请不要输入块。 bios[index]是“从biosindex位置给我孩子。 !==是“如果左侧不等于undefined的类型或值”。

bios[index].style.display="none" 这在上述条件之内,因此我们知道bios[index].style是未定义的。 我们将display样式设置为'hidden'以将其从用户的视图中隐藏。

我将以对您来说更有意义的方式对其进行重写:

function resetBioVisi() {
    var bioElem = document.getElementById("bio");
    var bios = bioElem.childNodes;

    for (var index = 0; index < bios.length; index++) {
        if (bios[index].style !== undefined) {
            bios[index].style.display="none";
        }
    }
}

有些人来的比较早,但是无论如何,这可以帮助您进一步了解它:

 function resetBioVisi() { // Get the bio element var bioElem = document.getElementById("bio"); // Get all the bio element's children var bios = bioElem.childNodes; // If there are no bio children, return since there's nothing to do if (bios.length == 0) return; // Else, loop through them and set their display style to none so they will not be rendered. for (var index = 0; index < bios.length; index++) if (bios[index].style !== undefined) bios[index].style.display="none"; } var button = document.getElementsByTagName('button')[0]; button.addEventListener('click', resetBioVisi); 
 <div id="bio"> <p>Bio 1</p> <p>Bio 2</p> <p>Bio 3</p> </div> <button>Hide bios</button> 

暂无
暂无

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

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