[英]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]
是“從bios
的index
位置給我孩子。 !==
是“如果左側不等於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.