开发者

Display a random item from an xml list

I've been looking all over, and I can't find a clean solution (that I can make sense of).

How can I pull an entry at random from an xml list?

My starting point is as follows (which pulls the latest entry):

<script type="text/javascript">
 var xmlDoc=null;
 if (window.ActiveXObject)
 {// code for IE
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
 }
 if (xmlDoc!=null)
 { 
  xmlDoc.async=fal开发者_运维知识库se;xmlDoc.load("/folder/file.xml");
  var x=xmlDoc.getElementsByTagName("z:row");
  for (i=0;i<1;i++)
  {
   document.write(x[i].getElementsByTagName("@ows_Title")[0]
    .childNodes[0].nodeValue);
  }
 }
</script>

Any and all suggestions greatly welcomed!


Math.random() will return a number between 0 and 1, and getElementsByTagName returns a NodeList that has a length. Thus,

Math.floor(Math.random() * x.length)

gives you a random index into the NodeList. You can then use this index to call item() to get that node out of the list:

var nodeList = xmlDoc.getElementsByTagName("whatever");
var node = nodeList.item(Math.floor(Math.random() * nodeList.length));


Change the code slightly... to switch "for (i=0;i<1;i++)" with "var i = Math.floor((Math.random()*1000)%x.length);"

<script type="text/javascript">
 var xmlDoc=null;
 if (window.ActiveXObject)
 {// code for IE
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
 }
 if (xmlDoc!=null)
 { 
  xmlDoc.async=false;xmlDoc.load("/folder/file.xml");
  var x=xmlDoc.getElementsByTagName("z:row");
  var i = Math.floor((Math.random()*1000)%x.length);
  {
   document.write(x[i].getElementsByTagName("@ows_Title")[0]
    .childNodes[0].nodeValue);
  }
 }
</script>

Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜