Jquery .load()仅适用于前6个元素,具有数据值

时间:2015-07-14 09:11:13

标签: javascript jquery

我有7个html div。如何使用data-recentviewes作为每个元素的加载URL,仅为前6个div加载一些动态数据?

HTML:

    <div id="recentViewes" data-recentviewes="/123/"></div>
    <div id="recentViewes" data-recentviewes="/456/"></div>
    <div id="recentViewes" data-recentviewes="/789/"></div>
    <div id="recentViewes" data-recentviewes="/321/"></div>
    <div id="recentViewes" data-recentviewes="/654/"></div>
    <div id="recentViewes" data-recentviewes="/987/"></div> <!-- 6 -->
---
    <div id="recentViewes" data-recentviewes="/abc/"></div> <!-- dont load this -->

js(仅适用于第一个元素):

window.addEventListener('load', function () {
    var recentviewes = $("#recentViewes").data('recentviewes');    
    $("#recentViewes").each(function(index, element) {
        $("#recentViewes").load("http://example.com" + recentviewes);                   

        return index < 5;
    });
}); 

感谢。

2 个答案:

答案 0 :(得分:5)

您需要删除(或修改)id属性,因为它们需要在文档上下文中是唯一的。这就是您的代码仅适用于第一个元素的原因。

您应该将它们更改为class属性。然后,您可以使用:lt选择器选择所需的元素:

<div class="recentViewes" data-recentviewes="/123/"></div>
<div class="recentViewes" data-recentviewes="/456/"></div>
<div class="recentViewes" data-recentviewes="/789/"></div>
<div class="recentViewes" data-recentviewes="/321/"></div>
<div class="recentViewes" data-recentviewes="/654/"></div>
<div class="recentViewes" data-recentviewes="/987/"></div> <!-- 6 -->

<div class="recentViewes" data-recentviewes="/abc/"></div> <!-- dont load this -->
window.addEventListener('load', function () {
    $(".recentViewes:lt(6)").each(function() {
        $(this).load("http://example.com" + $(this).data('recentviewes'));
    });
});

答案 1 :(得分:2)

使用class来分组相似的元素而不是ID,因为元素的ID必须是唯一的

<div class="recentViewes" data-recentviewes="/123/"></div>
<div class="recentViewes" data-recentviewes="/456/"></div>
<div class="recentViewes" data-recentviewes="/789/"></div>
<div class="recentViewes" data-recentviewes="/321/"></div>
<div class="recentViewes" data-recentviewes="/654/"></div>
<div class="recentViewes" data-recentviewes="/987/"></div>
<!-- 6 -->---
<div class="recentViewes" data-recentviewes="/abc/"></div>
<!-- dont load this -->

然后

$(window).load(function () {
    //get all elements with recentViewes class and take first 6 from that and loop
    $(".recentViewes").slice(0, 6).each(function (index, element) {
        //inside the loop use this to refer to the current recentViewes element and load the resource 
        $(this).load("http://example.com" + $(this).data('recentviewes'));
    });
});