javascript-将函数的结果显示为HTML

时间:2018-09-17 19:42:27

标签: javascript html

所以我有这个代码:

function check_total()
  {
   var inputElems = document.getElementsByTagName("input"),
    total = 0;

    for (var i=0; i<inputElems.length; i++) {       
       if (inputElems[i].type == "checkbox"){
          total++;
       }
    }
}   

document.getElementById('totalInput').innerHTML = total;

基本上,它计算我文档中复选框的数量。

我希望将结果(总计)显示在HTML的标题中。

到目前为止,我已经尝试过了,但是没有用:

<span id='totalInput'>default</span>

5 个答案:

答案 0 :(得分:2)

您的代码段中缺少一些内容。

首先,您需要将“ total”变量移至函数之外。通过成为全局变量,您将可以在以后的代码中使用它。

第二,您需要实际触发此函数,以便它执行并更新总变量。您可以使用

check_total();

就在document.getElementById ...行之前

最后,您可以使用document.querySelectorAll()函数简化此过程。这将返回所有匹配元素的数组,您可以简单地将其用作.innerHTML的一部分。通过使用此代码,您可以将所有代码替换为:

document.getElementById('totalInput').innerText = document.querySelectorAll("input[type=checkbox]").length;

最后,请注意,您可能应该使用.innerText而不是.innerHTML。使用innerHTML总是很危险的,因为有人可以在此处注入一些JavaScript。在这种情况下,由于您不想显示实际的HTML,只需使用.innerText即可执行相同的操作,但是使用文本而不是HTML。

这是一个有效的示例:https://jsbin.com/puhimip/edit?html,js,output

答案 1 :(得分:1)

您的示例看起来应该可以工作,除了您的代码中的代码之外,您永远不会从函数中返回任何内容。您还需要调用该函数以使其运行计算。

function check_total() {
    var inputElems = document.getElementsByTagName("input"),
    total = 0;

    for (var i=0; i<inputElems.length; i++) {       
       if (inputElems[i].type == "checkbox"){
           total++;
       }
    }
    return total;
}   

document.getElementById('totalInput').innerHTML = check_total();

请注意return末尾的check_total()语句。这样,您便可以将计算结果分配给所需的任何内容(在这种情况下,是其他元素的innerHTML属性)。

正如其他人所建议的那样,您也可以将总变量移出函数并移至所谓的全局范围中,但是出于种种原因,我们不建议这样做(请参见https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals )。

答案 2 :(得分:1)

尝试通过查询所有复选框从获得的NodeList中构建一个数组:

const countCheckboxes = () =>
  document.querySelectorAll('input[type=checkbox]')

const updateHeader = () =>
  document.getElementById('totalInput').textContent = countCheckboxes();

updateHeader();

如果您只想计数选中的复选框,则应使用Array.from

const isChecked = input =>
  input.checked

const checkedCheckboxes = () 
  Array.from(document.querySelectorAll('input[type=checkbox]'))
    .filter(isChecked)
    .length

答案 3 :(得分:1)

您试图将函数结果绘制到DOM中的行不在函数内部。将该行放入check_total()中(并记住也要调用该函数。)

function check_total() {
  var inputElems = document.getElementsByTagName("input"),
    total = 0;

  for (var i = 0; i < inputElems.length; i++) {
    if (inputElems[i].type == "checkbox") {
      total++;
    }
  }
  document.getElementById('totalInput').innerHTML = total; // this line was outside the function
}

check_total(); // call the function
<div><!-- for demo -->
<input type="checkbox">
<input type="radio">
<input type="checkbox">
<input type="text">
</div>

<span id='totalInput'>default</span>

答案 4 :(得分:0)

我还没有深入研究乔尔的答案,所以不知道这是否也解决了这个问题。 不过,我认为Tyr肯定在使用某些工具,而且我还想知道您是否真的想知道是否已选中复选框?

这是n个肮脏的镜头。

    <!DOCTYPE html>
    <html>

    <head>
        <script>
            document.addEventListener('DOMContentLoaded', function() {

                document.getElementById('doit').addEventListener('click', function() {
                    check_total();
                });

            });

            function check_total()
              {
               var inputElems = document.getElementsByTagName("input"),
                total = 0;

                for (var i=0; i<inputElems.length; i++) {       
                   if (inputElems[i].type == "checkbox"){
                      // do you want to check the the checkbox is checked, because it doesn't at the moment?
                      total++;
                   }
                }
                document.getElementById('totalInput').innerHTML = total;
            }   


        </script>
    </head>

    <body>
        <button id="doit">Do it</button><br />
        <input type="checkbox" /><br />
        <input type="checkbox" /><br />
        <div id="totalInput"></div>

    </body>

    </html>