所以我想使用Javascript选择要显示的XML数据(不使用属性)。以下是我想要做的具体细节:
XML
<channel>
<item>
<title>3.jpg</title>
<link>images/clean/3-dirty.jpg</link>
</item>
<item>
<title>4.jpg</title>
<link>images/clean/4-dirty.jpg</link>
</item>
<item>
<title>5.jpg</title>
<link>images/clean/4-clean.jpg</link>
</item>
<item>
<title>6.jpg</title>
<link>images/clean/4-dirty.jpg</link>
</item>
... and the list goes on for ages.
</channel>
的Javascript
<script type="text/javascript">
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","xml/drc.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{
document.write("<img src='");
document.write(x[i].getElementsByTagName("link")[0].childNodes[0].nodeValue);
document.write("' alt='image' height='220px' width='260px' />");
}
</script>
如何在网址中显示仅包含“脏”或“干净”字样的图像? 我尝试过使用IndexOf()方法但无法使用它。
答案 0 :(得分:3)
试试这个:
for (i=0;i<x.length;i++) {
var src = x[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
if( src.indexOf("dirty") != -1 ) {
document.write("<img src='");
document.write(src);
document.write("' alt='image' height='220px' width='260px' />");
}
}
如果它不起作用,也请尝试这个:
for (i=0;i<x.length;i++) {
var src = x[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
var srcLower = src.toLowerCase();
if( srcLower.indexOf("dirty") != -1 ) {
document.write("<img src='");
document.write(src);
document.write("' alt='image' height='220px' width='260px' />");
}
}