过去 3 个小时我一直在到处搜索,但找不到任何可以帮助我的东西。如果周围有任何答案,我感到非常抱歉,但我无法回答。
所以我有这个 xml 文件,例如:
<entry>
<title>The Title</title>
<description>Description here</description>
</entry>
所以我想做的事情是有一个带有搜索表单的 html,然后根据搜索词在同一页面(例如空 div)中显示与该词匹配的所有结果。
这可能吗?
非常感谢任何可以帮助我解决这个问题的人!
最佳答案
我对此感到好奇,但没有人回答,所以我尝试了一些东西并调整了最好和最简单的方法来做到这一点是使用 jQuery
测试.xml
<item>
<entry>
<title>The Title</title>
<description>Description here</description>
</entry>
<entry>
<title>The Title 2 </title>
<description>Description here second</description>
</entry>
</item>
index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="text" id="search" autocomplete="off" />
<p id="output"></p>
<script type="text/javascript">
$(document).ready(function(){
$('#search').on('keyup', function(){
$.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: parseXML
});
});
});
function parseXML(xml){
var searchFor = $('#search').val();
var reg = new RegExp(searchFor, "i");
$(xml).find('entry').each(function(){
var title = $(this).find('title').text();
var titleSearch = title.search(reg);
var desc = $(this).find('description').text();
var descSearch = desc.search(reg);
$('#output').empty();
if(titleSearch > -1){
$('#output').append('Found <i>'+searchFor+'<\/i> in title: '+title.replace(reg, '<b>'+searchFor+'</b>')+'<br \/>');
}
if(descSearch > -1){
$('#output').append('Found <i>'+searchFor+'<\/i> in description: '+desc.replace(reg, '<b>'+searchFor+'</b>')+'<br \/>');
}
});
}
</script>
</body>
</html>
关于javascript - 搜索 XML 文件并使用 javascript 显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12118057/