jquery - 使用 jQuery 获取随机项

标签 jquery ajax

刚刚开始学习使用 jQuery 的 ajax 请求。我尝试查看其他帖子,但不确定如何实现。这是我的代码。现在它刚刚获得前 3 件元素。我希望它从它拉动的 rss feed 中获取 3 个随机项目。这是我所拥有的:

jQuery(document).ready(function($) {
    $.ajax({
        url: "http://thrive.local/wp-content/themes/thriveafrica/fetcher.php",
        type: "GET",
        success: function(d) {
                $('item', d).slice(0, 3).each(function() {
                    var $item = $(this);
                    var title = $item.find('title').text();
                    var link = $item.find('link').text();
                    var description = $item.find('description').text();
                    var image = $(description).find('img').attr('src');
                    var price = $(description).find('span.SalePrice').text();
                    if (price == '') {price = 'Visit Store for Price'};

                    var html = '<li><a href="'+link+'" target="_blank">';
                    html += '<div class="image"><img src="'+image+'"></div>';
                    html += '<div class="info"><strong>'+title+'</strong><br/>'+price+'</div>';
                    html += '</a></li>';

                    // Example Output
                    // <li>
                // <div class="image"><img src="http://www.thriveafricastore.com/product_images/s/041/coffee__59525_thumb.jpg"></div>
                // <div class="info"><strong>Thrive Africa Blend (1lb)</strong><br>See Price</div>
              // </li>


                    $('div#store ul').append($(html));
                }); //End Each
        } //End Success
    }); // End Ajax Request
});

我有什么选择?

谢谢!

最佳答案

我会使用类似filter()的东西,而不是 slice(),在您的范围内生成 3 个唯一数字后:

var rnd1, rnd2, rnd3, undef,
    items = $('item', d);

// Generate our random numbers:
rnd1 = Math.floor(Math.random()*items.length);
while (rnd2 == undef || rnd2 == rnd1)
    rnd2 = Math.floor(Math.random()*items.length);
while (rnd3 == undef || rnd3 == rnd1 || rnd3 == rnd2)
    rnd3 = Math.floor(Math.random()*items.length);

//filter our items, only the ones whose index matches one of our randoms:
items.filter(function (index) { 
    return index == rnd1 || index == rnd2 || index == rnd3;
}).each(function {
    // rest of code...
});

请注意,如果返回的项目数小于 3,这将陷入无限循环,因为它会生成 0 - 项目长度 范围内的 3 个唯一数字。如果可能的话,您可以去掉 while 循环,只生成 3 个非唯一的随机数。

这是一个使用以下代码随机删除 3 个 div 的示例: http://jsfiddle.net/dAjAt/ 。继续单击运行按钮以查看其运行情况。

关于jquery - 使用 jQuery 获取随机项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3684035/

相关文章:

javascript - 如何制作 Jquery Popup 便签

javascript - ANGULAR2 如何保留滚动位置以防页面从 AJAX 加载

javascript - 如何在新的 Chrome 窗口中从 AJAX 响应打开 PDF blob

Javascript 或 JQuery 思维导图插件

javascript - 淡入和淡出图像的问题

javascript - 旋转文本保持宽度

jquery - CSS 位置失败

ruby - 其他部分不适用于 Rails ajax 形式

jquery - iphone safari webkit 与 mac safari 的区别

javascript - 延迟加载 "responsive"图片(未知高度)