2017-03-23 42 views
1

夥計們,我是Javascript新手,並且通過研究瞭解代碼中的所有內容,但是我不明白[9]和[12]行對代碼實際做了什麼。我的猜測是,當按鈕被按下時,它會調用id「msg」,但那會怎樣呢?所有的幫助表示讚賞。這條JavaScript代碼實際上做了什麼?

<!DOCTYPE html> 
<html> 
<body> 


<p>Click the button to sort the array.</p> 

<button onclick="RearrangeArray()">Rearrange Array</button> 

<p id="msg"></p> 



<script> 

var products = ["Printer", "Tablet", "Router", "Computer","TV"]; 
document.getElementById("msg").innerHTML = products; 

function RearrangeArray() { 
    products.sort(); 
    document.getElementById("msg").innerHTML = products; 
} 

</script> 

</body> 
</html> 
+0

Stackoverflow不是這個問題的正確渠道。如果你真的不知道這是幹什麼的,爲什麼你不運行這個代碼,並且你可能會喜歡這樣的教程:https://www.w3schools.com/js/default.asp –

+2

看到輸出? – Nicholas

+0

我知道代碼是如何工作的,它重新排列了數組,但是調用id「msg」並使用.innerHTML並與產品等同的是什麼呢? –

回答

2

查找<element id="msg"></element>,無論它在裏面,都可以用變量products中的任何內容進行擦除和替換,並解析出我們在其中找到的任何HTML。

0

它找到一個Id爲「msg」的元素並將其值設置爲產品,這是對數組的引用。

基本文件意味着this

getElementById是一個在HTML中定位元素的函數。

您可以將innerHTML理解爲元素的內容/值。

0
<p>Click the button to sort the array.</p> 

// create a new button 
// when a user clicks this button, call the RearrangeArray function 
<button onclick="RearrangeArray()">Rearrange Array</button> 

// create a new paragraph element and set its id to "msg" 
// by doing so, you can get a reference to this element and modify the contents 
// or attributes using javascript 
<p id="msg"></p> 


<script> 

// define an array containing the following strings 
var products = ["Printer", "Tablet", "Router", "Computer","TV"]; 

// get the paragraph element defined earlier, then set its innerHTML 
// property to the products 

// because products is not a string, it is coerced to a string by 
// joining each of the elements with a comma 
document.getElementById("msg").innerHTML = products; 


// defines a function that is available globally 
// the button above refers to this function in the 'onclick' handler 
function RearrangeArray() { 

    // sorts the array of products above using the javascript array sort function 
    // the products should now look like this: ["Computer", "Printer", "Router", "TV", "Tablet"] 
    products.sort(); 

    // get the element with the id of "msg" (which you defined above) 
    // and set its html to the now-sorted array of products (coerced as a string) 
    document.getElementById("msg").innerHTML = products; 
} 

</script> 
0

所有的HTML標籤可以有一個id屬性,並在網頁中必須是唯一的,這是方法,你可以保存HTML標籤的DOM對象使用the document.getElementById("ID_value")的變量之一。此外,DOM對象的innerHTML屬性將HTML存儲在此Object的適當標記內。

所以,這一行:

document.getElementById("msg").innerHTML = products; 

意味着該產品陣列的值存儲爲具有msg ID標籤內的普通的HTML。

相關問題