在javascript中动态获取元素ID

时间:2019-12-28 21:38:10

标签: javascript html getelementbyid

我正在尝试在单板计算机上建立一个简单的本地站点,以帮助我认识的人,从而帮助他们跟踪销售情况。

在此过程中,我一直遇到麻烦,特别是从<td>标记中获取数字时。它们看起来像这样:

<th>Tacos(s) :</th>
<td id="tacNum"></td>

这是有问题的功能:

function getTotal() { 
  var total = 0;
  for(i = 0; i < items.length; i++) {
    // This sets the correct ID with the help of the items[] array defined elsewhere
    var code = items[i] + "Num";

    // This sets the correct price of the item with the prices[] array defined elsewhere
    var priNum = prices[i];

    // Supposed to get the number of the items sold, uses the code variable to get the correct ID
    var tmp = document.getElementById(code).value;

    // Where I discovered that the tmp variable is not being defined properly 
    //alert(tmp);

    // This gets the total earned via the purchases and adds tax
    tmp = tmp * priNum;
    tmp = tmp + (tmp * taxRate);

    // total is defined elsewhere and is what supposed to be returned to the user
    total = total + tmp;
  }
}

虽然我能够以当前的方式获取正确的元素ID,但是在设置tmp变量时,它总是返回未定义状态。

我做错了什么?

编辑: 当用户Yevgen GorbunkovVLAZ回答时,我需要使用.textContent而不是.value

0 个答案:

没有答案