javascript 如何在 document.getElementById 中使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20303963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:11:06  来源:igfitidea点击:

How do I use variables in document.getElementById

javascriptvariablesgetelementbyid

提问by user3052776

I have this code which I've been trying to fix for hours.

我有这个代码,我已经尝试修复了几个小时。

<script language="JavaScript">
    <!--

    function generate(){
    var titels = new Array();
    var i = 0;
    for(i;i<9;i++){
    var test = 'h1-0'+ i;
        titels[i] = document.getElementById(test).textContent;
    }

    document.getElementById("uitkomst").value = titels[1];      
    }
    -->
</script>

This gives me the error

这给了我错误

TypeError: document.getElementById(...) is null
titels[i] = document.getElementById(test).textContent;

But when I change 'h1-0'+i by 'h1-0'+5 it does work and I don't get an error, so how do I fix this? Why is Javascript so annoying when using variables?

但是,当我将 'h1-0'+i 更改为 'h1-0'+5 时它确实有效并且我没有收到错误消息,那么我该如何解决这个问题呢?为什么 Javascript 在使用变量时如此烦人?

回答by Pointy

Add another variable:

添加另一个变量:

  var element;

and use it in the loop to hold on to the result of fetching (or trying to fetch) the element:

并在循环中使用它来保持获取(或尝试获取)元素的结果:

for (i; i < 9; i++) {
  element = document.getElementById('h1-0' + i);
  if (element) {
    titles[i] = element.textContent;
  }
  else {
    console.log("Element " + i + " not found.");
  }
}

Then check the console to see which one is missing.

然后检查控制台以查看缺少哪个。

回答by jfriend00

There are a couple ways you can fix this issue - you can test for a missing object and skip that case or you can catch the exception that is thrown and act accordingly in the exception handler.

有几种方法可以解决此问题 - 您可以测试丢失的对象并跳过该情况,或者您可以捕获抛出的异常并在异常处理程序中采取相应的行动。

Here's how you could handle missing objects in your code:

以下是处理代码中丢失对象的方法:

function generate(){
    var titels = [];
    var i, item, test;
    for (i = 0; i < 9; i++) {
        test = 'h1-0'+ i;
        item = document.getElementById(test);
        if (item) {
            titels[i] = item.textContent;
        }
    }
    document.getElementById("uitkomst").value = titels[1];      
}

If, this is really all your code is doing, then you don't need the forloop because you're only using the [1]item from the array and you can do this:

如果这真的是您的代码所做的全部,那么您不需要for循环,因为您只使用[1]数组中的项目,您可以这样做:

function generate() {
    var item = document.getElementById("h1-01");
    if (item) {
        document.getElementById("uitkomst").value = item.textContent;
    }

}