duanchi1230
2013-09-17 16:39
浏览 112

使用jquery for循环获取值

I have several item in a databse, I'm displaying a link with in the href the id of each item.

So I want to get the id from a href which is in a PHP while loop. So I did a for loop to do it but it seems to only get the first href attr.

for (var i = 0; i < check; i++) 
{
   var id = $(".id").attr('href');
   console.log(id);
} 

Check is equal to the number of columns in the database depends of a special id. In this case check = 3

The link is: echo '<a id="dislike" class="btn-primary btn pull-right id" href="'.$items['id'].'">Dislike</a>';

Any idea of why it doesn't work ?

I got them all!

But how can I make them go out of the function ?

function checkingfetchresult(userid){

    $.post("ajax/checkingfetchresult.php", { userid: userid },
            function(check){
            $(".id").each(function(){
                var id = $(this).attr('href');
            });

    });

}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongtuo6562 2013-09-17 16:43
    已采纳

    You are selecting the same elements on each iteration and then getting the attribute of the first element in the set. Instead of looping like that, you should use each:

    $(".id").each(function(){
       var id = $(this).attr('href');
       console.log(id);
    });
    
    已采纳该答案
    打赏 评论
  • doujieyu7062 2013-09-17 16:42

    You're getting the first element every time, and logging its href. You can't expect a loop to behave differently if it's doing the same thing every time?

    If you want to get all the href attributes for all the .id elements, use map:

    $('.id').map(function () { return $(this).attr("href") });
    

    It will return an array, where each element is the href of the corresponding .id element.

    打赏 评论
  • duanchan5458 2013-09-17 16:44

    $(".id") returns an array-like object, containing all of the matching elements. what you actually want to do is this:

    var idArray = $(".id");
    for (var i = 0; i < check; i++) {
        var id = $(idArray[i]).attr('href');
        console.log(id);
    } 
    
    打赏 评论

相关推荐 更多相似问题