开发者

javascript for loop adding issue - creating custom jQuery paging

Need a hand with some javascript and maybe its a friday thing, but im stuck...

I am making a custom jQuery carousel and im tring to make dynamic paging.

To simplify the issue (have added hard coded values), at the moment this code:

for(var i = 0; i < 3; i++) {
 $('.paging').append('<a href="#" rel="0">Test</a>');
}

outputs:

<a href="#" rel="0">Test</a>
<a href="#" rel="0">Test</a>
<a href="#" rel="0">Test</a>

Whereas I need the code to output like:

<a href="#" rel="0">Test</a>
&l开发者_C百科t;a href="#" rel="200">Test</a>
<a href="#" rel="400">Test</a>

I can I adjust the for statement above so that it adds 200 everytime it loops through?

Any help would be much appreiated.

A.


You can do it more easily with the $(html, props) notation and .appendTo(), like this:

for(var i = 0; i < 3; i++) {
  $('<a />', { href: '#', text: 'Test', rel: i*200 }).appendTo('.paging');    
}

You cant test it out here. If you're looping through a lot though, I'd advise caching the .paging selector, like this:

var p = $('.paging');
for(var i = 0; i < 3; i++) {
  $('<a />', { href: '#', text: 'Test', rel: i*200 }).appendTo(p);    
}


Try this:

var str = '';
for(var i = 0; i < 3; i++) {
 str +='<a href="#" rel="' + i * 200 + '">Test</a>';
}

$('.paging').append(str)

Appending once should be better for performances.


multiply the counter (i) by 200

for(var i = 0; i < 3; i++) {
 $('.paging').append('<a href="#" rel="'+i*200+'">Test</a>');
}


Try this:

for(var i = 0; i < 3; i++) {
   var rel = i * 200;
   $('.paging').append('<a href="#" rel="' + rel + '">Test</a>');
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜