能够为" name"分配任何值。但是无法为其分配document.getElementById(' name')?

时间:2015-09-06 07:15:44

标签: javascript

我正在尝试将document.getElementById(' name')分配给' name'但它没有被分配为什么?

<body>
  <h1>Hello World</h1>
  <input type="text" id="name">
  <script type="text/javascript">
    var name;
    console.log('before change name = ',  name);// [object HTMLInputElement]
    name = 'change value of name';
    console.log('after change name = ', name);//change value of name. name is changeable here
    name = 5;
    console.log('again change name = ', name);// 5. name is changeable here 
    var worker = new Worker('/js/worker.js');
    name = document.getElementById('name');//name is not changeable here why ?
    console.log('assign input name value name = ', name);//[object HTMLInputElement]
    name.onkeyup = function(){
      worker.postMessage({msg:'send to worker'});
    };
    worker.onmessage = function(e){
      console.log(e.data, 'from worker');
    };
  </script>
</body>

我只想让document.getElementById('name')访问name,但此行name = document.getElementById('name')name的原因没有影响?

2 个答案:

答案 0 :(得分:0)

您已将带有id="name"的DOM元素分配给name。你想要的可能是DOM元素的当前值。

name = document.getElementById('name').value;

编辑:

由于您需要将附加事件处理程序添加到元素,因此您需要使用addEventListener()方法:

name = document.getElementById('name');
name.addEventListener("keyup", function() {
    worker.postMessage({msg:"'send to worker'});
});

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener?redirectlocale=en-US&redirectslug=DOM%2FEventTarget.addEventListener

答案 1 :(得分:0)

这一切都取决于你要分配的内容。你的问题不是很清楚。

如果您要设置&#39; name&#39;的值(元素)到&#39; name&#39;的值(javascript变量),你会使用:

document.getElementById("name").value = name;

如果您要设置&#39; name&#39;的值(变量)到&#39; name&#39;的值(元素),您将使用:

name = document.getElementById("name").value; //(As shown in the previous answer)

如果您要显示&#39; name&#39;的值(变量)在(p,li,td等)的innerHTML中你将使用:

document.getElementById("name").innerHTML = name;