代码之家  ›  专栏  ›  技术社区  ›  F0l0w

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

  •  1
  • F0l0w  · 技术社区  · 7 年前

    所以我有这个密码:

    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 回复  |  直到 7 年前
        1
  •  2
  •   Joel Lord    7 年前

    代码片段中缺少一些东西。

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

    其次,您需要实际触发这个函数,以便它执行并更新total变量。你可以这样做

    check_total();
    

    最后,您可以使用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

        2
  •  1
  •   Daniel Beck    7 年前

    您试图将函数结果绘制到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>
        3
  •  1
  •   Julian Suggate    7 年前

    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 另一个元素的属性)。

    正如其他人所建议的,您还可以将total变量从函数中移出,放入所谓的 全局范围 https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals ).

        4
  •  1
  •   Benny Powers    7 年前

    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
    
        5
  •  0
  •   HoldOffHunger Lux    5 年前

    我对乔尔的回答没有看得太深,所以不知道这是否也解决了这个问题。

        <!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 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>