0

請告訴我下面差X =的document.getElementById( 「ID」)。的className =&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> 

在第二個下拉菜單中工作正常。 在第一種情況下,即使x是全局變量也不行。

我是新來的JavaScript,我無法找出原因。 有人可以推理嗎?

PS:我用W3-CSS

回答

4

在第一變,你的變量xclassName字符串的一個副本。您對x所做的任何更改都將針對該變量,而不是原始的className屬性值。

在第二個變體中,變量xgetElementById返回的對象引用的副本。只要您沒有爲x分配新值,它就會指向DOM對象。任何突變完成到x(即通過分配給它的一個屬性,如className)將影響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)的關鍵。

相關問題