JavaScript的Element.value VS Element.getAttribute(QUOT;价值") [英] JavaScript Element.value vs Element.getAttribute("value")

查看:141
本文介绍了JavaScript的Element.value VS Element.getAttribute(QUOT;价值")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习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值。

的jsfiddle DEMO

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.

jsFiddle DEMO

这篇关于JavaScript的Element.value VS Element.getAttribute(QUOT;价值&QUOT;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆