设置给定标签的html内容
Setting the html content of a given tag
我正在尝试使用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;
,这就是为什么你不会在页面上看到它们的内容。
长话短说:不要在脚本标签里放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"
获得一个错误。
相关文章:
- 如何根据html内容使用ng类-AngularJS
- JavaScript在其他页面上用html内容填充文本框
- Rails:如何在浏览器中显示动态html内容,而不会对其进行转义,也不会引起XSS攻击
- 使用javascript动态创建html内容/元素
- 无法将大型html内容POST到Chrome上的服务器
- 使用li元素的html内容更改该元素的背景
- 如何从ajax返回两个html内容
- jQuery获取子DIV的HTML内容
- HTML内容下推到固定背景图像下方
- 在angular中,使用ng repeat生成动态html内容
- 使用$watch更改html内容
- 如何使用window.showModalDialog()显示HTML内容
- 如何在使用 UIWebView 编辑 HTML 内容时正确调整输入语言更改 (LTR/RTL) 的文本对齐方式
- 获取垂直溢出容器的 html 内容
- 为数组中的每个项目追加 html 内容
- Dojo:在 iframe 加载时解析 HTML 内容
- 允许 Itemp 在 Enyo 中使用 HTML 内容
- 从选项卡中获取 HTML 内容
- 可以将HTML内容放在画布上(登录页)
- 只有当类是硬编码的时,才可以使用jQuery来显示/隐藏html内容