我有带有前缀“ add-product-”标签的输入框ID,并且我什么都不想替换“ add-product-”。所以我尝试使用,data[field.id].replace("add-product-", "");
但这给了我错误:[Error] TypeError: undefined is not an object (evaluating 'data[field.id].replace')
这是我的代码:
function addproduct(){
var datafeilds = Array.from(document.querySelectorAll("[id^='add-product-']"));
var data = {};
datafeilds.forEach(function(field){
data[field.id].replace("add-product-", "");
data[field.id] = field.value;
});
console.log(data);
}
输出为:
[Log] {add-product-name: "", add-product-overlay1: "", add-product-overlay2: "", add-product-wholesale_price: "", add-product-delivery_price: "", …}
我希望它是:
[Log] {name: "", overlay1: "", overlay2: "", wholesale_price: "", delivery_price: "", …}
您可以replace
在再次添加到空obj中之前使用。另外,默认情况下Array.From
,您不需要在datafeilds
as中使用querySelectorAll返回nodes
数组中的所有。
运行下面的代码片段,查看其是否正常运行并全部替换。
function addproduct() {
var datafeilds = document.querySelectorAll("[id^='add-product-']")
var data = {};
datafeilds.forEach(function(field) {
//replace all add-products with ""
var replace = field.id.replace("add-product-", "");
//Push to data {}
data[replace] = field.value
});
console.log(data)
}
addproduct()
<input id='add-product-name' value="1" />
<input id='add-product-overlay1' value="1" />
<input id='add-product-overlay2' value="1" />
<input id='add-product-wholesale_price' value="1" />
<input id='add-product-delivery_price' value="1" />
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句