[英]Convert input field clearing from jQuery to Javascript
My trouble is not with the action of clearing the input field - I know the elem.value = ""
I am having more trouble getting the right selector in Javascript. 我的麻烦不是清除输入字段的动作-我知道
elem.value = ""
我在使用Javascript获取正确的选择器时遇到了更多麻烦。
While my jQuery works fine on the site - all other function are in Javascript, so I would like to keep consistency since it isn't that difficult. 尽管我的jQuery在该网站上运行良好,但其他所有功能均使用Javascript,因此我想保持一致性,因为它并不那么困难。
Here is the jQuery : 这是jQuery :
function clearShipToFields(){
$('input.ship_to_value').each(function(){
this.value = "";
});
}
what I was trying to do in Javascript but wasn't working: 我试图用Javascript做的但没有用的东西:
var shipTo = document.getElementsByClassName('ship_to_value');
//This is where I am stuck - I don't know how to single out input fields only
I may need to go a different direction and get the input fields first and then filter by class? 我可能需要走一个不同的方向,首先获取输入字段,然后再按类进行过滤?
var inputFields = document.getElementsByTagName('input');
For Loop
inputFields[i].getElementsByClassName('ship_to_value').value = "";
End For
There are multiple fields with the class ship_to_value
but I would only like to select the input
field. 类
ship_to_value
有多个字段,但我只想选择input
字段。
Must also support pre-IE8 还必须支持IE8之前的版本
getElementsByClassName
returns an array, as such you can access it by index: getElementsByClassName
返回一个数组,因此您可以通过索引访问它:
var shipTo = document.getElementsByClassName('ship_to_value')[0];
shipTo.value = '';
If you have multiple elements with that class, you would need to implement your code in a loop: 如果该类具有多个元素,则需要循环执行代码:
var elements = document.getElementsByClassName('ship_to_value');
for (var i = 0; i < elements.length; i++) {
elements[i].value = '';
}
I only want to select the fields that are input elements
我只想选择作为输入元素的字段
In this case you would need to inspect the tagName
property of the element first: 在这种情况下,您需要首先检查元素的
tagName
属性:
var elements = document.getElementsByClassName('ship_to_value');
for (var i = 0; i < elements.length; i++) {
elements[i].tagName == 'INPUT' && (elements[i].value = '');
}
您可能希望查看querySelector
和querySelectorAll
,但是请注意检查那些链接中的支持网格。
var shipTo = document.querySelector('input.ship_to_value');
I prefer to use querySelectorAll
with a prototype loop to iterate DOM elements. 我更喜欢使用带有原型循环的
querySelectorAll
来迭代DOM元素。
Array.prototype.forEach.call(document.querySelectorAll("input.ship_to_value"), function(x) {
x.value="";
});
Alternatively you can use [].forEach.call
instead of Array.prototype.call
或者,您可以使用
[].forEach.call
而不是Array.prototype.call
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.