getElementById有时有效,有时无效't

getElementById sometimes works, and sometimes doesn't

本文关键字:有效 getElementById 无效      更新时间:2023-09-26

我正在开发一个小型的Windows8应用程序,遇到了这个非常烦人的问题。首先这里是HTML:

<h2 id="name" class="article-title win-type-ellipsis" data-win-bind="textContent: title"></h2>
<h4 id="price" class="article-subtitle" data-win-bind="textContent: price"></h4>

这是JavaScript:

order.addEventListener("click", function (e) {
    Data.add(document.getElementById("price").innerText);
    var name = document.getElementById("name").innerText;
    var msg = Windows.UI.Popups.MessageDialog(name + " added.");
    msg.showAsync();
});

JavaScript在获取"price"元素时正常工作,但由于某种原因,在获取"name"元素时决定不工作,我只收到消息"added"。

没有其他ID为"name"的元素,我完全不明白为什么这不起作用。

EDIT:对于我提供的代码中为什么两个HTML标记都是空的,似乎有一些困惑。我绑定了另一个JavaScript文件中的文本,所有这些都在工作,因为当我运行应用程序时,这些标记中有文本,唯一的问题是由于某种原因,我能够获取price元素,但不能获取name元素。

尝试以下HTML:

<h2 id="name" class="article-title win-type-ellipsis" data-win-bind="textContent: title"></h2>
<h4 id="price" class="article-subtitle" data-win-bind="textContent: price">0.00</h4>

在这种情况下,内部文本是html标记之间的内容。由于您没有内部文本,因此消息无法显示任何内部文本。