代码最后一行报错,Can not read property of undefined (reading 'insertAdjacentHTML')
有没有人帮忙看一下怎么解决
哥们,下面是修改后的代码,你试试看,有问题欢迎追问!
function addLine() {
var maxNumber = 0;
// 使用原生Javascript获取所有匹配的div元素
var divs = document.querySelectorAll('div[id^="detail table"]');
divs.forEach(function (div) {
var id = div.id;
// 使用正则表达式匹配id中的数字部分
var match = id.match(/detail table (\d+)$/);
if (match) {
var number = parseInt(match[1], 10);
if (number > maxNumber) {
maxNumber = number;
}
}
});
var newNumber = maxNumber + 1;
var newId = 'detail table ' + newNumber;
var newDivHtml = '<div id="' + newId + '" data-role="collapsible" data-collapsed="false" data-content-theme="b" data-theme="b">';
newDivHtml += '<h3>No.' + newNumber + '</h3>';
newDivHtml += '<input type="button" value="行追加" onclick="addLine()">';
newDivHtml += '<input type="button" value="行削除" onclick="delLine(' + newNumber + ')">';
newDivHtml += '<div data-role="fieldcontain"><label for="receipt attached">文件上传</label><input type="file" id="xxx image' + newNumber + '" name="xxx image' + newNumber + '"/></div>';
//..·其他元素的添加
newDivHtml += '</div>'; // 结束div标签
// 找到最后一个div元素的父元素
var lastDiv = document.querySelector('div[id^="detail table"]');
if (!lastDiv) {
console.error('No div with id starting with "detail table" found.');
return;
}
var parent = lastDiv.parentNode;
// 检查新id是否唯一
if (document.getElementById(newId)) {
console.error('Error: An element with id "' + newId + '" already exists.');
} else {
// 将新创建的div添加到父元素中
parent.insertAdjacentHTML('beforeend', newDivHtml);
}
}
function delLine(lineNumber) {
// 删除对应行号的div元素
var divs = document.querySelectorAll('div[id^="detail table"]');
divs.forEach(function (div) {
var id = div.id;
var match = id.match(/detail table (\d+)/);
if (match && parseInt(match[1], 10) === lineNumber) {
div.parentNode.removeChild(div);
}
});
}