点击随机从xml随机化javascript

时间:2011-05-05 21:18:35

标签: javascript jquery html xml

我正在尝试使用单击按钮创建基于xml的图像显示。

所以,在我的外部xml文件中,我有以下内容:

<?xml version="1.0" encoding="utf-8"?>
<gallery>
    <photo name="summer">
        <file>imageone.jpg</file>
    </photo>
    <photo name="winter">
        <file>image2.jpg</file>
    </photo>
    <photo name="sprint">
        <file>3.jpg</file>
    </photo>
    <photo name="fall">
        <file>four.jpg</file>
    </photo>
</gallery>

在网页上,我想要一个按钮,点击它会从上面的列表中随机播放并随机显示其中一个图像以及相应的照片名称节点。

我已经研究过各种jquery xml解析器,但是我遇到了随机问题。这可能吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

检索照片数组后,只需生成一个随机数,然后选择一个:

$photos = $(xmldata).find('photo');
$randomImage = $photos.eq(Math.floor(Math.random() * $photos.length));

$name = $randomImage.attr('name');
$img = $randomImage.find('file').text();

答案 1 :(得分:0)

我建议:

1) read all image names with any parser into array
2) randomize the array with jQuery
3) select and use 1