【问题标题】:How to insert dynamic string into HTML [duplicate]如何将动态字符串插入 HTML [重复]
【发布时间】:2021-05-19 17:23:17
【问题描述】:

我正在尝试创建一个 JS 函数,该函数采用 JS 数组并使用内容创建 HTML 表,但是当我尝试使用代码时,该表未显示在我的网站上。这是我正在使用的函数,我尝试使用按钮调用该函数:

<input type = "button" onclick = "makeTableHTML()" value = "Display">

<script> 
    function makeTableHTML() {
        var result = "<table class=\"table table-bordered table-striped\">";
        result += "<thead>";
        result += "<tr>";
        result += "<th>RIF</th>";
        result += "<th>Nombre</th>";
        result += "</tr>";
        result += "</thead>";
        result += "<tbody id=\"myTable\">";                    
        for(var i=0; i<arreglo_rif.length; i++) {
            result += "<tr>";
            result += "<td>"+arreglo_rif[i]+"</td>";
            result += "<td>"+arreglo_nombre[i]+"</td>";                                
            result += "</tr>";
        }
        result += "</tbody>";
        result += "</table>";
        console.log(result);
        return result;
    }
</script>

但是当我点击按钮时,表格也不显示。

【问题讨论】:

  • 你创建了一个 HTML 字符串,但你没有用它做任何事情
  • return result; 更改为document.body.appendChild(result);,以便表格添加到页面底部。
  • 另外,如果你想把引号放在其他引号里面,你可以在双引号里面使用单引号,而不是用\"转义引号,例如:"&lt;tbody id='myTable'&gt;"
  • 感谢大家的帮助。另外,感谢 Scott Marcus 的理解。我可以看到我的问题本可以更清楚,但至于研究工作,我已经尝试了几件事,在这里提出我的问题是一种最后的恢复。不是每个人都是天生的专家。

标签: javascript html


【解决方案1】:

var arreglo_rif=['one','two','three']
var arreglo_nombre=[1,2,3]

function makeTableHTML() {
    var result = "<table class=\"table table-bordered table-striped\">";
    result += "<thead>";
    result += "<tr>";
    result += "<th>RIF</th>";
    result += "<th>Nombre</th>";
    result += "</tr>";
    result += "</thead>";
    result += "<tbody id=\"myTable\">";                    
    for(var i=0; i<arreglo_rif.length; i++) {
        result += "<tr>";
        result += "<td>"+arreglo_rif[i]+"</td>";
        result += "<td>"+arreglo_nombre[i]+"</td>";                                
        result += "</tr>";
    }
    result += "</tbody>";
    result += "</table>";
    
    document.getElementById('container').innerHTML = result;
    
}
<input type = "button" onclick = "makeTableHTML()" value = "Display">

<div id='container'></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-23
    • 2014-11-11
    • 1970-01-01
    • 2018-12-04
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多