返回false的每个循环仅显示第一个结果

时间:2015-04-27 18:50:17

标签: jquery

我想在按钮点击时显示10个条目(类“马”)的得分和用户名,它连接图像的alt和title标签中的值,附加到每个条目的类“lane”。如果我包含“return false”来结束each()循环,则此函数仅显示每个条目上 first 条目的值。如果我排除return false,则所有值都会显示在所有条目上。我需要帮助,了解如何只显示相应条目上每个条目的值。

按要求添加HTML示例:

<div id="lane10" class="lane">
 <img class="horse" id="car10" alt="James Hinchcliffe" title="560 pts" src="indyNewGunMetal.png"/>
</div>
$('.showLabels').on('click', Labels);

function Labels() {
    $('.horse').each(function() {
        var imgTitle = (AJS.$(this).attr('title'));
        var imgAlt = (AJS.$(this).attr('alt'));     
        var fullTag = "<div class='carLabel'>" + imgAlt + "&nbsp;-&nbsp;"
                          + imgTitle + "</div>";

        // show image title
        AJS.$('.lane').before(fullTag); 

        // return false stops the each loop.        
        return false;

    });
};

2 个答案:

答案 0 :(得分:1)

如果你需要使用你在每个元素上应用的函数的返回布尔值,你应该使用谓词:

$('.showLabels').on('click', Labels);
var predicate = true;
function Labels() {
    $('.horse').each(function () {
        var imgTitle = (AJS.$(this).attr('title'));
        var imgAlt = (AJS.$(this).attr('alt'));
        var fullTag = "<div class='carLabel'>" + imgAlt + "&nbsp;-&nbsp;" + imgTitle + "</div>";
        AJS.$('.lane').before(fullTag);
        predicate = predicate && false;
    });
};

//do something with predicate

这只是一个想法,“false”将始终将您的谓词更改为false,而不是“false”,您应该使用您需要在那里使用的任何条件。

答案 1 :(得分:0)

试试此代码

$('.showLabels').on('click', Labels);
function Labels() {
$('.horse').each(function(i,val) {
var imgTitle = (AJS.$(this).attr('title'));
var imgAlt = (AJS.$(this).attr('alt'));     
var fullTag = "<div class='carLabel'>" + imgAlt + "&nbsp;-&nbsp;"
                    + imgTitle + "</div>";

// show image title
AJS.$('.lane').before(fullTag); 

// return false stops the each loop.  
if(i==9)      
return false;

});
};
相关问题