我有这个代码,它有效,但想简化它。特别是,我相信有一种简短的方法来引用子元素,这样我就不需要编写多个函数了。如果有简化方法来简化此代码,请告诉我们!
目前的代码是
function getLineNumbers() {
var lineNumber = document.querySelectorAll('#InvoiceDetailGrid tbody tr td:nth-child(1)');
return Array.prototype.map.call(lineNumber, function(elem) {
return elem.textContent;
}); }
function getSKUs() {
var SKU = document.querySelectorAll('#InvoiceDetailGrid tbody tr td:nth-child(2)');
return Array.prototype.map.call(SKU, function(elem) {
return elem.textContent;
}); }
function getDescriptions() {
var description = document.querySelectorAll('#InvoiceDetailGrid tbody tr td:nth-child(3)');
return Array.prototype.map.call(description, function(elem) {
return elem.textContent;
}); }
function getPrices() {
var price = document.querySelectorAll('#InvoiceDetailGrid tbody tr td:nth-child(4)');
return Array.prototype.map.call(price, function(elem) {
return elem.textContent;
}); }
function getQuantities() {
var quantity = document.querySelectorAll('#InvoiceDetailGrid tbody tr td:nth-child(5)');
return Array.prototype.map.call(quantity, function(elem) {
return elem.textContent;
}); }
function getTotals() {
var total = document.querySelectorAll('#InvoiceDetailGrid tbody tr td:nth-child(6)');
return Array.prototype.map.call(total, function(elem) {
return elem.textContent;
}); }
然后我在稍后的函数中使用以下代码调用它:
lineNumber = lineNumber.concat(this.evaluate(getLineNumbers));
SKU = SKU.concat(this.evaluate(getSKUs));
description = description.concat(this.evaluate(getDescriptions));
price = price.concat(this.evaluate(getPrices));
quantity = quantity.concat(this.evaluate(getQuantities));
total = total.concat(this.evaluate(getTotals));
有没有办法简化这段代码所以我只需要一个函数(例如,getInvoiceData)将子元素正确地链接到正确的数组?
答案 0 :(得分:1)
您已经使用函数(CSS选择器:nth-child()
)来选择特定的子元素。您只能有一个函数,并通过单独的参数将预期的子索引传递到页面上下文中:
function getText(i) {
var elements = document.querySelectorAll('#InvoiceDetailGrid tbody tr td:nth-child('+i+')');
return Array.prototype.map.call(elements, function(elem) {
return elem.textContent;
});
}
lineNumber = lineNumber.concat(this.evaluate(getText, 1));
SKU = SKU.concat(this.evaluate(getText, 2));
...