设置给定标签的html内容

Setting the html content of a given tag

本文关键字:html 内容 标签 设置      更新时间:2023-09-26

我正在尝试使用javascript生成html页面的内容。我需要替换的标签内容是第二个标签中的内容:

<script id="accountview" type="text/view">
    <!-- We show the menu bar regardless of the window we are viewing as long as we are logged in -->
    <div class="panel">
      <button onclick="go_home()">Home</button>
      <button onclick="go_browse()">Browse</button>
      <button onclick="go_account()">Account</button>
    </div>
    <div id="welcome" class="welcome">
    <!-- Content to be replaced -->
    </div>
</script>

我使用下面的函数来生成内容:

function go_account()
{
    // Get the currently logged in user's data(name, surname, e-mail, country, city)
    var userData = serverstub.getUserDataByToken(localStorage.getItem("current_user")).data;
    // To get the actual user attributes use ".": userData.firstname
    var userInfo = "<div class='"welcome'"> User Information: <br>";
    userInfo += "email:" + userData.email + "<br>";
    userInfo += "firstname:" + userData.firstname + "<br>";
    userInfo += "lastname:" + userData.lastname + "<br>";
    userInfo += "gender:" + userData.gender + "<br>";
    userInfo += "city:" + userData.city + "<br>";
    userInfo += "country:" + userData.country + "<br>";
    userInfo += "</div>";
    // Change the <div> with the user info
    var element = document.getElementById("welcome");
    element.innerHTML = userInfo;
}

,但是返回的元素总是null。为什么?

脚本标记内的任何内容都被视为CDATA。在W3术语中,这意味着它不会被解析为HTML,而是作为原始文本。然而,脚本标签的默认样式是display: none;,这就是为什么你不会在页面上看到它们的内容。

https://stackoverflow.com/a/5679857/2813263

长话短说:不要在脚本标签里放HTML

不确定我是否正确理解您,但仅仅是因为您在功能结束时缺少return element;吗?在JavaScript中,你必须显式返回,不像其他语言。

编辑说:

我重读了你的问题,问题确实是(就像雅克在另一个答案中解释的),你的脚本标签的内容不被视为HTML。

请参阅此JSFiddle以获取该问题的较小示例:https://jsfiddle.net/Lxyamptk/

和查看这个JSFiddle使用jQuery的一个可能的解决方案:https://jsfiddle.net/Lkd180zk/

HTML:

<script id="accountview" type="text/view">
  <div>
    <div id="welcome" class="welcome"></div>
  </div>
</script>
<div id="output">
    output goes here
</div>

JS with jQuery:

var templateAsText = $("#accountview").html();
var templateAsHTML = $(templateAsText);
templateAsHTML.find("#welcome").text("Welcome!");
$("#output").html(templateAsHTML);

注意,对于$(templateAsText)工作,模板必须有一个HTML元素作为它的根(就像我的例子中的包装器div)。例如,您将从templateAsText = "hello <div></div> hello"获得一个错误。