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)的关键。

相关问题