JavaScript的Element.value VS Element.getAttribute(QUOT;价值") [英] JavaScript Element.value vs Element.getAttribute("value")
问题描述
我已经开始学习JavaScript近日但有我很困惑的东西:
之间有什么不同的 Element.value
和 Element.getAttribute(值)
其实我的问题是,当我尝试复制输入
类型文本元素
来的值另外一个,如果我用第一种方法( Element.value
),它工作正常,但如果我用第二种方法去拷贝它的第一个值永远不会给予元素,并将其当我改变了文本
中的文本被更新,这种行为似乎有些奇怪我!你们可以请解释一下这是怎么回事呢?
< HTML和GT;
< HEAD>
<间的charset =UTF-8>
<标题>您好JavaScript的< /标题>
&所述; SCRIPT SRC =script2.js>&下; /脚本>
< /头>
<身体GT;
<输入ID =文本1类型=文本/>
<输入ID =Button1的类型=按钮值=键/>
<输入ID =文本2类型=文本/>
< /身体GT;
< / HTML>
JavaScript文件:
VAR myButton的;在window.onload =函数(){ myButton的=的document.getElementById(Button1的);
myButton.onclick =功能(){
VAR VAL =的document.getElementById(文本1)的getAttribute(值)。
// VAR VAL =的document.getElementById(文本1)值;
。的document.getElementById(文本2)的setAttribute(价值,VAL);
};};
不同的是, element.value
是实时的,如果用户更改比方说,一个文本框输入时,它会反映,并告诉你新的价值。
在的getAttribute('值')
仍将显示原来的值=whateverWasHere
值。
I've started learning JavaScript recently but there's something that I'm confused with :
what is the different between Element.value
and Element.getAttribute("value")
?
actually my problem is , when I try to copy the value of an input
element with type of text
to another one , if I use the first method (Element.value
) It works fine but if I go with the second method It copies the first value given to the element and It never gets updated when I change the text inside the textbox
, this behavior seems odd to me ! can you guys please explain what's going on here ?
<html>
<head>
<meta charset="utf-8">
<title>Hello JavaScript</title>
<script src="script2.js"></script>
</head>
<body>
<input id="Text1" type="text" />
<input id="Button1" type="button" value="button" />
<input id="Text2" type="text" />
</body>
</html>
The JavaScript file :
var myButton;
window.onload = function () {
myButton = document.getElementById("Button1");
myButton.onclick = function () {
var val = document.getElementById("Text1").getAttribute("value");
//var val = document.getElementById("Text1").value;
document.getElementById("Text2").setAttribute("value", val);
};
};
The difference is that element.value
is real time and if a user changes let's say, a textbox input, it will reflect that, and show you the new value.
While getAttribute('value')
will still show the original value="whateverWasHere"
value.
这篇关于JavaScript的Element.value VS Element.getAttribute(QUOT;价值&QUOT;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!