为什么我无法通过javascript更改文本字段的值?

时间:2017-01-04 09:25:51

标签: javascript html input

我尝试按标记名称获取标记并更改该值,是否可以帮助我找到为什么这不起作用?



var r_capacity=document.getElementsByName("capacity");
function expireOtherFildes(){r_capacity.value="";}

ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:3)

你需要使用它:

var r_capacity=document.getElementsByName("capacity")[0];

document.getElementsByName("capacity")会返回nodeList。 可以通过索引号访问节点。

var r_capacity=document.getElementsByName("capacity")[0];
function expireOtherFildes(){r_capacity.value="";}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>

答案 1 :(得分:2)

document.getElementsByName返回数组。您可以通过index.Refer访问它 -

var r_capacity=document.getElementsByName("capacity");
function expireOtherFildes(){
  
  r_capacity[0].value="";
   

}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>

答案 2 :(得分:1)

您需要使用

var r_capacity = document.getElementsByName("capacity")[0];

因为var r_capacity = document.getElementsByName("capacity");它返回了 nodeList ,您可以使用index 0来访问它:

&#13;
&#13;
var r_capacity = document.getElementsByName("capacity")[0];
console.log(r_capacity);

function expireOtherFildes() {
  r_capacity.value = "";
}
&#13;
ID:
<input type="text" name="id" class="textBox" onFocus="expireOtherFildes()" />capacity:
<input type="text" name="capacity" value="xxx" />
&#13;
&#13;
&#13;

更好的做法是使用querySelector(),这样可以避免遇到问题:

&#13;
&#13;
   var r_capacity = document.querySelector("input[name='capacity']");
   console.log(r_capacity);

   function expireOtherFildes() {
     r_capacity.value = "";
   }
&#13;
ID:
<input type="text" name="id" class="textBox" onFocus="expireOtherFildes()" />capacity:
<input type="text" name="capacity" value="xxx" />
&#13;
&#13;
&#13;

答案 3 :(得分:1)

document.getElementsByName()返回NodeList数组。您需要选择第一个索引,或者只需切换到document.getElementById()

var r_capacity=document.getElementsByName("capacity")[0];
                                                  //-^^^
 console.log(r_capacity);
function expireOtherFildes(){r_capacity.value="";}
ID: <input type="text" name="id" class="textBox" onFocus="expireOtherFildes()"/>
capacity: <input type="text" name="capacity" value="xxx"/>