使用空白模板 我的 default.html 有以下内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HiThere</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.2.0/js/base.js"></script>
<script src="//Microsoft.WinJS.2.0/js/ui.js"></script>
<!-- HelloWorld references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<br />
<h1 id="msg" />
<br />
<button id="btn">Say Hello</button>
</body>
</html>
我的默认.css
body { }
这里是default.html
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
"use strict";
var app = WinJS.Application;
app.onactivated = function (args) {
WinJS.UI.processAll().done(
function () {
var btn = document.getElementById("btn");
btn.addEventListener("click", btnClick);
});
};
function btnClick(mouseEvent) {
document.getElementById("msg").innerText = "Hello there";
}
app.start();
})();
问题是,当我单击按钮时,会显示 Hello there 文本,但按钮会消失。有人可以提供任何想法,因为我做错了什么导致按钮不显示。
最佳答案
您的问题出在标记上——不要在 HTML 文档中使用 XML 标记。
当浏览器看到:
<h1 />
它只找到一个 H1 开始标签(/
没有意义)并且在找到结束标签或匹配 </
之前不会关闭该元素。 .如果没有找到,它将回退到纠错。可能(虽然不确定)浏览器正在图灵:
<h1 id="msg" />
<br />
<button id="btn">Say Hello</button>
进入:
<h1 id="msg">
<br>
<button id="btn">Say Hello</button>
</h1>
所以当你替换 innerText (符合 W3C 的等价物是 textContent )H1 的全部内容被替换为提供的文本,导致:
<h1 id="msg">Hello there</h1>
XML 风格的标记可以或应该用于 HTML 文档是一种常见的误解,但这是 XHTML 时代将 HTML 转换为 XML 的失败尝试所造成的谬论。在 HTML 文档中使用 HTML 标记,为 XML 文档保存 XML。
关于javascript - 为什么在正确更新标签文本的单击事件后按钮本身不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23984944/