在网站的输入框中填充JavaScript(Chrome控制台)改进问题

92dk7w1h  于 9个月前  发布在  Go
关注(0)|答案(1)|浏览(172)

我已经为一个网站创建了一个脚本,它根据上面的标题(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;
    }
}

字符串
它运行得很好。我的字典代码如下:

代码嗅探器

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">&nbsp;<br>
  <h3>Value1:</h3>
  <input type="text" name="q1" id="q1">
  <h3>Value2:</h3>
  <input type="text" name="q2" id="q2">
</div>
c2e8gylq

c2e8gylq1#

考虑到你提供的HTML,这是可以简化的。首先,由于inputh3元素的兄弟元素,那么你可以简单地使用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;
  }
}

个字符

相关问题