下面的代码有什么不同:
<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
发布于 2017-10-14 20:07:52
在第一个变体中,变量x是className字符串的副本。对x所做的任何更改都是对该变量的更改,而不是对原始className属性值的更改。
在第二个变体中,变量x是getElementById返回的对象引用的副本。只要您不给x分配一个新值,它就会指向DOM对象。对x所做的任何更改(例如,将其属性分配给它的一个属性,比如className)都会影响DOM对象,因此这种效果在web文档中是可见的。
发布于 2017-10-14 20:30:44
你的问题说得不对。区别在于
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";通过使用+=算子,您创建了一个新字符串,然后将该字符串分配给x.className。这是因为x上的属性"className“是对象的属性映射到字符串值"bar”(关于对象属性的更多信息)的键。
发布于 2018-03-16 08:26:14
我问这样一个问题太愚蠢了。这里的问题是,x返回一个字符串,它是一个独立的副本,相反,如果我只返回x,document.getElementById('id')将重调一个通过引用传递的对象,因此x可以被修改。
https://stackoverflow.com/questions/46748822
复制相似问题