0

いただきましX =のdocument.getElementById( "ID")の差。クラス名=&x =のdocument.getElementById( "ID")、x.className =

<div class="w3-dropdown-click"> 
    <button class="w3-btn" onclick="clickDrp()">Hover Over me</button> 
    <div class="w3-dropdown-content w3-animate-zoom w3-bar-block" id="cont">   
     <a href="#" class="w3-bar-item w3-button">SomeLink1</a> 
     <a href="#" class="w3-bar-item w3-button">SomeLink2</a> 
     <a href="#" class="w3-bar-item w3-button">SomeLink3</a> 
     <a href="#" class="w3-bar-item w3-button">SomeLink4</a> 
    </div> 
</div> 
<script type="text/javascript"> 
    function clickDrp(){ 
     var x = document.getElementById("cont").className; 
     if(x.search("w3-show") == -1) 
      x += " w3-show"; 
     else 
      x = x.replace(" w3-show",""); 
    } 
</script> 

と以下のコードの差

<div class="w3-dropdown-click"> 
    <button class="w3-btn" onclick="clickDrp()">Hover Over me</button> 
    <div class="w3-dropdown-content w3-animate-zoom w3-bar-block" id="cont">   
     <a href="#" class="w3-bar-item w3-button">SomeLink1</a> 
     <a href="#" class="w3-bar-item w3-button">SomeLink2</a> 
     <a href="#" class="w3-bar-item w3-button">SomeLink3</a> 
     <a href="#" class="w3-bar-item w3-button">SomeLink4</a> 
    </div> 
</div> 
<script type="text/javascript"> 
    function clickDrp(){ 
     var x = document.getElementById("cont"); 
     if(x.className.search("w3-show") == -1) 
      x.className += " w3-show"; 
     else 
      x.className = x.className.replace(" w3-show",""); 
    } 
</script> 

2番目のドロップダウンメニューで問題なく動作します。 xがグローバル変数にされても、最初はそれはありません。

私はjavascriptを使いましたが、その理由を理解することができません。 誰かがそれを推論できますか?

PS:私は最初の変形ではW3-CSS

答えて

4

を使用しました、あなたの変数xclassName文字列のコピーです。 xに行った変更は、元のclassNameプロパティ値ではなく、その変数になります。

第2の変形では、変数xは、getElementByIdが返すオブジェクト参照のコピーです。 xに新しい値を割り当てない限り、DOMオブジェクトを指します。 の突然変異xに行われた場合(つまり、classNameなどのプロパティの1つに代入すると)DOMオブジェクトに影響し、その結果がWebドキュメントに表示されます。

+0

xがグローバル変数の場合はどうなりますか? –

+0

@PrajvalMは違いはありません。 – Pointy

+0

@PrajvalM、それは無関係です。文字列値を変数(ローカル、グローバル、またはオブジェクトのプロパティ - それは問題ではありません)に代入するときは、コピーを割り当てます。ストリングはプリミティブな値です(不変)。 'className'プロパティの値を変更する唯一の方法は、新しい文字列を割り当てることです。変数への代入でこれを行うことはできません。これは 'className'プロパティにする必要があります。 – trincot

0

ご質問が正しく行われていません。違いはここに

x = document.getElementById(“id”).className; 
x = ...; 

x = document.getElementById(“id”); 
x.className = ...; 

ある問題のシンプルな例です:

// Case 1 
var a = { foo: "bar" }; 
var b = a.foo; 
b += "baz"; 
console.log(a.foo); // "bar" 
console.log(b); // "barbaz" 

// Case 2 
var a = { foo: "bar" }; 
var b = a.foo; 
a.foo += "baz"; 
console.log(a.foo); // "barbaz" 
console.log(b); // "bar" 

割り当てa.foo += "baz";はあなたに、意味的にa.foo = a.foo + "baz";と同じであり、またはケース:

x.className = x.className + " w3-show"; 

+= operatorを使用すると、新しい文字列が作成され、その文字列がx.classNameに割り当てられました。これは、xのプロパティ "className"が、文字列値 "bar"(more on object properties)に対するオブジェクトのプロパティマップのキーであるという事実に起因します。

関連する問題