[英]How can i pass an attribute to a javascript function by reference?
I want to manipulate some attributes of my page elements in a java script function , take a look at this example and maybe you find a solution to do this. 我想在java脚本函数中操作我的页面元素的一些属性,看看这个例子,也许你找到了一个解决方案来做到这一点。
function doubleup(attr){
attr*=2;
}
doubleup(myDIV.style.zIndex);
doubleup(myDIV.style.opacity);
In short, you don't. 简而言之,你没有。 You can't pass primitive values by reference.
您无法通过引用传递原始值。 You can do that with non-primitive values, though, as they're always passed as reference.
但是,您可以使用非原始值执行此操作,因为它们始终作为引用传递。 Example:
例:
function doubleup(object, property) {
object[propety] *= 2;
}
doubleup(myDiv.style, "zIndex");
doubleup(myDiv.style, "opacity");
Primitive data types are strings, numbers, booleans and, recently, Symbol
s 原始数据类型是字符串,数字,布尔值,最近是
Symbol
You only pass the value of this attribute to the function, so you don't change the style element, you only change the value, can do it in this way: 您只将此属性的值传递给函数,因此您不更改样式元素,只更改值,可以这样做:
function doubleup(attr){
return attr*=2;
}
myDIV.style.opacity = doubleup(myDIV.style.opacity);
myDIV.style.zIndex = doubleup(myDIV.style.zIndex);
By the way, you have to use zIndex
instead of z-index
to manipulate this value. 顺便说一下,你必须使用
zIndex
而不是z-index
来操作这个值。
Another possible solution is: 另一种可能的解决方案
function doubleup(el){
el.style.opacity*=2;
}
function doubleupZIndex(el){
el.style.zIndex*=2;
}
doubleupOpacity(myDIV);
doubleupZIndex(myDIV);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.