简体   繁体   中英

How to loop through LI items in UL, get specific attributes, and pass them via $.ajax data

Here is my HTML code:

<ul id="gallery">
    <li id="attachment-32" class="featured"><a href="..." title=""><img src="..." alt="" /></a></li>
    <li id="attachment-34"><a href="..." title=""><img src="..." alt="" /></a></li>
    <li id="attachment-38"><a href="..." title=""><img src="..." alt="" /></a></li>
    <li id="attachment-64"><a href="..." title=""><img src="..." alt="" /></a></li>
    <li id="attachment-75"><a href="..." title=""><img src="..." alt="" /></a></li>
    <li></li>
</ul>

Here is my sample ajax request:

$.ajax({
    url: '/ajax/upload.php',
        type: 'POST',
    data: { ... },
        success: function(data){
        }
});

Here is what I want to achieve.

  1. How to get the attachment number in ID attribute for every LI inside the gallery UL only when an ID attr is there and pass them via ajax data in this way: { attached : '32,34,38,64,75' } if there is a better way of doing this let me know I want to pass the list items which contain attachments to process. I want to avoid LI items which are empty, do not include id attr.

  2. How to get the list item LI which has class of featured eg { featured_img : .. } and pass the attachment ID number if featured LI exists, and if none of list items is featured pass featured_img with 0. So i know how to process it via php in the request.

Any help is appreciated.

Thank you.

There's an .map for that:

var ids = $("#gallery li").map(function () {
    return this.id.split("-")[1];
}).get().join(",");

...

$.ajax({
    url: '/ajax/upload.php',
    type: 'POST',
    data: { ids: ids },
    success: function(data) {

    }
});

Demo.

Try this, May be help you.

var val = new Array();
$('#gallery li').each(function(){
    val.push($(this).attr('id'));
});
document.write(val);

Example to implement.

$.ajax({
    url: '/ajax/upload.php',
        type: 'POST',
    data: { attached : val },
        success: function(data){
        }
});

Hope this help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM