如何将 .xml 文件中的评论内容输出到文本区域?
我的.html:
<textarea name="comment" id="comment" rows="3"/>
我的.xml:
<div>
<ab type="transcription"><!--This is a comment--></ab>
</div>
我的.js:
$.ajax({
type: "GET",
url: "../data/cards/1799.xml",
dataType: "xml",
cache: false,
success: function (xml) {
[...]
var mycomment = $(xml).find("ab").attr("type", "transcription");
$("comment").val(mycomment)
.text() 不输出任何内容。预先感谢您对正确方向的任何提示!
最佳答案
您的 HTML 元素是 <textarea>
,不是<comment>
,所以$('comment').val
行不通的。另外,要获取评论的文本,您应该使用
$(xml).find('ab').text()
仅 - 使用 .attr
设置或获取节点的属性,您不关心该属性。所以,尝试:
const text = $(xml).find('ab').text();
$("#comment").val(text);
#
in front 表示您要查找具有该 id 的元素。 (如果没有任何符号,则表明您想要查找具有该标签名称的元素。)
在您的 XML 中,如果您想识别 ab
其类型为transcription
,您将使用查询字符串:
ab[type="transcription"]
另一个问题是text
(或 textContent
)不识别注释节点 - 但是,如果 <ab>
的内容只是该评论,那么您可以使用.html
或.innerHTML
来检索它。
另请注意,不需要为此包含像 jQuery 这样的大型库 - 您可以在普通 Javascript 中轻松实现它:
fetch(<url>)
.then(res => res.text())
.then((text) => {
const doc = new DOMParser().parseFromString(text, 'text/html');
const text = doc.querySelector('ab').innerHTML;
document.querySelector('#comment').value = text;
});
演示:
const responseText = `<div>
<ab type="transcription"><!` + `--This is a comment--></ab>
</div>`;
const doc = new DOMParser().parseFromString(responseText, 'text/html');
const text = doc.querySelector('ab').innerHTML;
document.querySelector('#comment').value = text;
<textarea id="comment"></textarea>
要访问评论节点的内容,可以使用childNodes[0]
导航到该节点,然后获取其 textContent
:
const responseText = `<div>
<ab type="transcription"><!` + `--This is a comment--></ab>
</div>`;
const doc = new DOMParser().parseFromString(responseText, 'text/html');
const text = doc.querySelector('ab').childNodes[0].textContent;
document.querySelector('#comment').value = text;
<textarea id="comment"></textarea>
关于javascript - 通过 ajax 调用在 XML 文件中输出注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910226/