javascript - 如何从 XML 中选择随机子元素并显示子子元素;使用 JS?
问题描述
我想从 XML 文件中获取数据以显示在通过单击按钮获得的 html 页面中。单击按钮时,我希望它选择一个随机子项,并显示子子项数据。我制作了一个如下所示的 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<kdramas>
<kdrama>
<title lang="en">A Gentleman's Dignity</title>
<genre>Comedy, Romance, Drama</genre>
<year>2012</year>
<episodes>20</episodes>
<about>This drama will tell the story of four men in their forties as they go through love, breakup, success and failure. </about>
</kdrama>
<kdrama>
<title lang="en">Boys Over Flowers</title>
<genre>Comedy, Romance, Drama, School</genre>
<year>2009</year>
<episodes>25</episodes>
<about>about text</about>
</kdrama>
<kdrama>
<title lang="en">Goblin</title>
<genre>Comedy, Romance, Melodrama, Supernatural</genre>
<year>2016</year>
<episodes>16</episodes>
<about>about text</about>
</kdrama>
单击按钮时,我能够显示 XML 数据,但它显示了所有数据(标题除外)。我环顾四周,看看是否可以选择一个随机子元素,然后显示其子子元素,但到目前为止,我没有任何运气找到任何东西。我必须显示 XML 数据的 JS 代码是:
function getDrama(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML =
this.responseText;
document.getElementById("content").style.display = "block";
}
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}
关于如何做到这一点的任何想法?或者甚至只是将我指向一个我可以阅读自己如何做的地方会很棒?
解决方案
使用 JQuery 构造 $(_your_text_).find('_elenent_name_') 查找数据:
function getDrama(_callback){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("content").innerHTML = this.responseText;
//document.getElementById("content").style.display = "block";
_callback(this.responseText);
}
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}
function get_random_title(){
getDrama(function(_text){
var titles_length = $(_text).find('kdrama').length;
var random_number = 1 + Math.floor(Math.random() * titles_length);
var random_title = $(_text).find('kdrama').eq(random_number).find('title').text();
$('#content').html( random_title );
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content"></div>
<input type="button" value="Get Random Title" onClick="get_random_title();">
推荐阅读
- python - Pandas 等效于带有列表/元组/迭代的 SQL 的“Where In”
- python - 程序的睡眠时间比预期的要长 - Python Tkinter
- r - 什么是几何形态学中的异速生长,使用 procD.lm 函数
- python - 使用标签更新 Tkinter 文本
- c++ - 循环包含在 MinGW 中的模板化函数
- load-testing - 将 Locust HTML 报告发送到 s3 存储桶
- google-cloud-platform - 检查 BigQuery 合并语句中的两个数组是否完全相同
- winforms - Webbrowser redirection issue C#
- python - How to build a path in my templates file for Django
- survey - 查找调查数据集的误差范围和显着性