我已经为一个网站创建了一个脚本,它根据上面的标题 (h3) 更新输入框。
为了避免出现多个 if,我决定创建一个字典,但出现错误:
未捕获的类型错误:无法设置 null 的属性(设置“值”)
我的第一个代码是:
var k = 1;
for (var i = 2; i < 29; i++) {
var j = i-k;
if(document.querySelector('h3:nth-child('+i+')'))
{
var value = document.querySelector('h3:nth-child('+i+')').innerHTML;
if( value.includes("Value1"))
{
document.querySelector('#q'+j).value = "random_value1";
}
else if( value.includes("Value2"))
{
document.querySelector('#q'+j).value = "random_value2";
}
else if( value.includes("Value3"))
{
document.querySelector('#q'+j).value = "random_value3";
}
else
{
// do nothing
}
k = k+1;
}
}
而且效果很好。我的字典代码在这里:
代码片段
const myself = {
Value1: "random_value1",
Value2: "random_value2",
Value3: "random_value3"
};
var k = 1;
for (var key in myself) {
console.log(key)
console.log(myself[key])
for (var i = 2; i < 29; i++) {
var j = i - k;
if (document.querySelector('h3:nth-child(' + i + ')')) {
var value = document.querySelector('h3:nth-child(' + i + ')').innerHTML;
if (value.includes(key)) {
console.log("true")
document.querySelector('#q' + j).value = myself[key];
} else {
// do nothing
}
k = k + 1;
}
}
}
<div class="html_form"> <br>
<h3>Value1:</h3>
<input type="text" name="q1" id="q1">
<h3>Value2:</h3>
<input type="text" name="q2" id="q2">
</div>
根据您提供的 HTML,这可以简化。首先,由于
input
是 h3
元素的以下同级元素,因此您可以简单地使用 nextElementSibling()
而不必将选择器字符串拼凑在一起,或用不必要的属性混淆 HTML。
此外,您可以使用单个循环遍历对象属性来查找匹配的
h3
元素并根据需要执行更新。
这是一个工作示例:
const h3 = document.querySelectorAll('.html_form > h3');
const myself = { Value1: "random_value1", Value2: "random_value2", Value3: "random_value3" };
for (const [key, value] of Object.entries(myself)) {
const target = [...h3].find(el => el.textContent.includes(key));
if (target) {
target.nextElementSibling.value = value;
}
}
<div class="html_form">
<br>
<h3>Value1:</h3>
<input type="text" name="q1" id="q1">
<h3>Value2:</h3>
<input type="text" name="q2" id="q2">
</div>