Frage

I'm trying to increment a margin-left value with each passing of a loop. How is this achieved?

Here's the JSFiddle and here's what I'm trying to do:

var myObj = {
    "dog":"pony",
    "sass":"tude",
    "war":"peace"
};

for (i in myObj) {
    $('#mainDiv').append("<p>" + i + "</p>");
    $('p').css("marginLeft","++20px");
}

How to have each <p> tag incremented by 20px more than the <p> tag before it?

War es hilfreich?

Lösung 2

You can use a variable outside of the loop to keep track of something incrementing. You also weren't properly getting the right p tag in your loop, if I'm understanding you correctly.

var myObj = {
    "dog":"pony",
    "sass":"tude",
    "war":"peace"
};

var lastMargin = 0;
for (i in myObj) {
    $('#mainDiv').append("<p class='"+i+"'>" + i + "</p>");
    lastMargin += 5;
    $("."+i).css("marginLeft",lastMargin+"px");
}

You obviously might want to use :nth-child with the i variable instead of classes.

Andere Tipps

Change

$('p').css("marginLeft","++20px");

to

$('p').each(function() {
    var thisp = $(this);
    thisp.css("marginLeft", thisp.css("marginLeft") + 20);
});

Create a var that keep the count.

Also, only aim for the last p (last one added):

var myObj = {
        "dog":"pony",
        "sass":"tude",
        "war":"peace"
    },
    count = 0; 

for (i in myObj) {
    $('#mainDiv').append("<p>" + i + "</p>");
    $('p').last().css("marginLeft",(20 * count) + 'px');
    count++
}

Fiddle : http://jsfiddle.net/3hxDK/4/

It seems like you're trying to have each subsequent paragraph indented more than the last?

If so, you need to reference the paragraph on its own.

var count = 0;

for (i in myObj) {
    $("<p>" + i + "</p>").
      css('marginLeft', count + "px").
      appendTo($('#mainDiv'));

    count += 20;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top