开发者

Generate Buttons with jQuery

开发者 https://www.devze.com 2023-01-12 05:38 出处:网络
Is it possible to create a certain number of \'buttons\' based on the number of images with jQuery? example:

Is it possible to create a certain number of 'buttons' based on the number of images with jQuery?

example:

<ul class="gallery">
    <li>&l开发者_Go百科t;img src="example-one.png" /></li>
    <li><img src="example-two.png" /></li>
    <li><img src="example-three.png" /></li>
</ul>

Is there a way to create three nav buttons without adding any more html? I usually do the programming end of sites and not the javascript - jQuery is still new to me.

I know that:

var imageCount = jQuery('.gallery li').length;

will give me the number of images, but I'm lost on where to go from there.

Edit:

The output that I'm trying to achieve is something like:

<ul class="gallery">
    <li><img src="example-one.png" /></li>
    <li><img src="example-two.png" /></li>
    <li><img src="example-three.png" /></li>
</ul>
// Added with jQuery
<ul class="gallery-nav">
    <li><a href="#">Button One</a></li>
    <li><a href="#">Button Two</a></li>
    <li><a href="#">Button Three</a></li>
</ul>

Whereby the .gallery-nav would be used to navigate through the images (i.e. clicking 'Button Two' would display example-two.png)


Where would you like your buttons to go? If you want to do something for each of something of another thing, you can use jQuery's .each() method like this:

$('.gallery img').each(function() {
    alert("This is image " + $(this).attr('src'));
});

And here's an example of how to do it: http://jsfiddle.net/3HeFS/


You mean this:

var imageCount = jQuery('.gallery li').length;

for(var i=0; i<imageCount; i++){
 $('button').appendTo($('body'));
}

You can replace the $('body') above to append the buttons elsewhere too since you have not mentioned where you want to place those buttons.


var names = ['One', 'Two', 'Three'];
$('.gallery li').each(function(i, el) {

    var oldHtml = $(this).html();
    $(this).empty().html('<a href="#">Button '+names[i]+'</a>');


});​

example

0

精彩评论

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