2017-03-23 8 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

"msg"というIDを持つ要素を見つけ、その値を製品の値に設定します。これは配列への参照です。

基本的には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属性を持つことができますし、Webページに、それは一意である必要があり、これはあなたがthe document.getElementById("ID_value")を使用して変数にHTMLタグのDOMオブジェクトを保存することができる方法の一つです。また、DOMオブジェクトのinnerHTMLプロパティは、このObjectの適切なタグの内部にHTMLを格納します。

ので、この行:

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

は、製品の配列の値がmsg IDを持っているタグ内のプレーンなHTMLとして保存されていることを意味します。

関連する問題