x = document.getElementById(“id”)之间的区别.className =& x = document.getElementById(“id”),x.className =

时间:2017-10-14 20:01:50

标签: javascript jquery html javascript-events javascript-objects

以下代码的差异是什么

<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

3 个答案:

答案 0 :(得分:4)

在第一个版本中,您的变量xclassName字符串的副本。您对x所做的任何更改都将是该变量,而不是原始的className属性值。

在第二个变体中,变量xgetElementById返回的对象引用的副本。只要您不为x分配新值,它就会指向DOM对象。对x执行的任何变异(即通过分配其属性之一,如className)将影响DOM对象,因此效果将在Web文档中可见。

答案 1 :(得分: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。这源于财产&#34; className&#34; on x是对象属性映射中的一个键,用于字符串值&#34; bar&#34; (more on object properties)。

答案 2 :(得分:0)

我提出这样一个问题是愚蠢的。事情是x这里返回一个字符串,它是一个单独的副本,相反,如果我只返回x作为document.getElementById('id')将返回一个通过引用传递的对象,因此可以修改x。

相关问题