开发者

Using javascript to insert id into list elements

开发者 https://www.devze.com 2023-02-21 21:32 出处:网络
I am messing around with a deck of cards that I made.I have it set up so that there is a method that spits out cards by suit into a list, so if I want spades I get a <ol> of all of the spades ca

I am messing around with a deck of cards that I made.I have it set up so that there is a method that spits out cards by suit into a list, so if I want spades I get a <ol> of all of the spades cards. I am now trying to give each <li> element an id depending on what card it is. ace will be <li id="ace"><img src="ace_spades.gif"/></li> king will be <li id="king"><img src="king_spades.gif"/></li> for example.The list is in order from top to bottom akqj1098765432 . I tried doing this:

var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12)
    {
    $(document).ready(function(){
    $("li").eq(counter).attr("id", card_id[counter])
        });
    counter++;
    }

but it doesn't work. I have not really done anything with javascript before besides simple jquery stuff. What 开发者_JS百科am I getting wrong here?


Try this:

$(document).ready(function(){
    var card_id = ["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
    $.each(card_id, function(i,id){
        $("li").eq(i).attr('id',id);
    });
});

You should try to only have one $(document).ready() function and it's not necessary to use a while() loop.


I think you don't need to call $(document).ready() function in the while. Try this:

var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12){
    $("li").eq(counter).attr("id", card_id[counter]);
    counter++;
 }


You do not need the document ready function. Place your script just before </body> and after the jquery.js script. This is working for me.

Check working example at http://jsfiddle.net/H8MeG/2/


First of ID's in a webpage have to be unique. Some browsers might ignore id's of elements that have already been used. Other browsers might fail completely... Second off. you shouldn't use .eq() like that. You definitely shouldn't add 12 new $(document).ready() statements.

Here's a more reliable version and the example on jsfiddle

var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$("#spades li").each(function(index){
    $(this).attr("class", card_id[index]);
    $(this).text(card_id[index]);
});

I also added $(this).text(card_id[index]); so you see it actually works. Try to uses classes for multiple elements that share the same characteristic.


why are you messing with ids at all? you know that the first item is the ace, the second the king, and so on. ol.getElementsByTagName('li')[12]='deuce'

0

精彩评论

暂无评论...
验证码 换一张
取 消