-1

Why does this won't work?

var data = {"one": [
    {"slot1":true, "app":"facebook"},
    {"slot2":true, "app2": "facebook"}
]};

$(data.one).each(function() {
    if(this.slot1==true){
        $('#dropable').find('.1_1').append('<img src="img/apps/' + this.app1 + '.png" alt="' + this.app1 + '">');
    }
    if(this.slot2==true){
        $('#dropable').find('.1_2').append('<img src="img/apps/' + this.app2 + '.png" alt="' + this.app2 + '">');
    }
});

my #dropable:

<div id="dropable" class="drag"><div class="app 1_1"></div></div>
<div id="dropable" class="drag"><div class="app 1_2"></div></div>
5
  • 1
    What do you mean by "doesn't work"? What does it do, what doesn't it do, what should it do? Commented Feb 28, 2013 at 15:24
  • out comes: <img alt="undefined" src="img/apps/undefined.png"> but it should be display: <img alt="facebook" src="img/apps/facebook.png"> Commented Feb 28, 2013 at 15:25
  • 1
    this.app1 is undefined, but it should have still worked, it just would have given you the text "undefined" as alt text and the image name which should have been clearly visible with inspect element. Commented Feb 28, 2013 at 15:26
  • 1
    Also, classes cannot start with a number. Commented Feb 28, 2013 at 15:28
  • Please notice that its called droppable Commented Feb 28, 2013 at 15:42

2 Answers 2

2

You have two DIVs with the same ID. Try changing '#dropable' to '.drag'.

Sign up to request clarification or add additional context in comments.

Comments

1

There are multiple issues with this code.

First $().each is for DOM elements, not for your own arrays/objects. You want $.each. Second, this.app1 doesn't exist in your object, you have app and app2.

Lastly, and most importantly, you have 2 IDs of dropable. You can't do that. IDs are supposed to be unique. Use a class instead of an ID.

<div class="drag"><div class="app 1_1"></div></div>
<div class="drag"><div class="app 1_2"></div></div>

And then do it like this:

var data = {"one": [
    {"slot1":true, "app1":"facebook"},
    {"slot2":true, "app2":"facebook"}
]};

$.each(data.one,function() {
    if(this.slot1==true){
        $('.drag').find('.1_1').append('<img src="img/apps/' + this.app1 + '.png" alt="' + this.app1 + '">');
    }
    if(this.slot2==true){
        $('.drag').find('.1_2').append('<img src="img/apps/' + this.app2 + '.png" alt="' + this.app2 + '">');
    }
});

2 Comments

thx works perfectly. But I have one more question. Can I count maybe with a for loop the '.1_1' and '.1_2' ... ?
@Evolutio: You can do $('.drag').find('.app').each( to loop over each of the .app elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.