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

92dk7w1h  于 2024-01-04  发布在  Go
关注(0)|答案(1)|浏览(284)

我已经为一个网站创建了一个脚本,它根据上面的标题(h3)更新输入框。
为了避免有多个if,我决定创建一个字典,但我得到一个错误:
未捕获的TypeError:无法设置null的属性(设置“value”)
我的第一个代码是:

  1. var k = 1;
  2. for (var i = 2; i < 29; i++) {
  3. var j = i-k;
  4. if(document.querySelector('h3:nth-child('+i+')'))
  5. {
  6. var value = document.querySelector('h3:nth-child('+i+')').innerHTML;
  7. if( value.includes("Value1"))
  8. {
  9. document.querySelector('#q'+j).value = "random_value1";
  10. }
  11. else if( value.includes("Value2"))
  12. {
  13. document.querySelector('#q'+j).value = "random_value2";
  14. }
  15. else if( value.includes("Value3"))
  16. {
  17. document.querySelector('#q'+j).value = "random_value3";
  18. }
  19. else
  20. {
  21. // do nothing
  22. }
  23. k = k+1;
  24. }
  25. }

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

代码嗅探器

  1. const myself = {
  2. Value1: "random_value1",
  3. Value2: "random_value2",
  4. Value3: "random_value3"
  5. };
  6. var k = 1;
  7. for (var key in myself) {
  8. console.log(key)
  9. console.log(myself[key])
  10. for (var i = 2; i < 29; i++) {
  11. var j = i - k;
  12. if (document.querySelector('h3:nth-child(' + i + ')')) {
  13. var value = document.querySelector('h3:nth-child(' + i + ')').innerHTML;
  14. if (value.includes(key)) {
  15. console.log("true")
  16. document.querySelector('#q' + j).value = myself[key];
  17. } else {
  18. // do nothing
  19. }
  20. k = k + 1;
  21. }
  22. }
  23. }
  1. <div class="html_form">&nbsp;<br>
  2. <h3>Value1:</h3>
  3. <input type="text" name="q1" id="q1">
  4. <h3>Value2:</h3>
  5. <input type="text" name="q2" id="q2">
  6. </div>
c2e8gylq

c2e8gylq1#

考虑到你提供的HTML,这是可以简化的。首先,由于inputh3元素的兄弟元素,那么你可以简单地使用nextElementSibling(),而不必拼凑一个选择器字符串,或者用不必要的属性混淆HTML。
此外,您可以使用一个循环遍历对象属性,查找匹配的h3元素,并在需要时执行更新。
下面是一个工作示例:

  1. const h3 = document.querySelectorAll('.html_form > h3');
  2. const myself = { Value1: "random_value1", Value2: "random_value2", Value3: "random_value3" };
  3. for (const [key, value] of Object.entries(myself)) {
  4. const target = [...h3].find(el => el.textContent.includes(key));
  5. if (target) {
  6. target.nextElementSibling.value = value;
  7. }
  8. }

个字符

相关问题