我已经为一个网站创建了一个脚本,在那里它更新了上面的标题(H3)的输入框.
为了避免有多个if,我决定创建一个字典,但收到一个错误:
未捕获的TypeError:无法设置Null的属性(设置‘Value’)
我的第一个代码是:
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;
}
}
而且它运行得很好.我的词典代码如下:
Code Snippet个
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>