【问题标题】:Setting the html content of a given tag设置给定标签的 html 内容
【发布时间】:2015-11-24 17:33:11
【问题描述】:

我正在尝试使用 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;
}

但返回的元素始终为空。为什么?

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    不确定我是否理解正确,但仅仅是因为您在函数末尾缺少return element; 吗?在 JavaScript 中,您必须显式返回,这与其他一些语言不同。

    编辑说:

    我重新阅读了您的问题,问题确实是(就像 Jacque 在另一个答案中解释的那样)您的脚本标签的内容不被视为 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>
    

    带有 jQ​​uery 的 JS:

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

    请注意,要使$(templateAsText) 正常工作,模板必须有一个 HTML 元素作为其根(如我示例中的包装器 div)。例如,您会收到来自templateAsText = "hello &lt;div&gt;&lt;/div&gt; hello" 的错误。

    【讨论】:

    • 不,我已经添加了return语句,但元素仍然为null。
    【解决方案2】:

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

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

    长话短说:不要将 HTML 放在脚本标签中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      • 2014-02-10
      • 2013-05-06
      • 2011-08-23
      • 1970-01-01
      • 2018-06-22
      • 2011-12-03
      相关资源
      最近更新 更多