简体   繁体   English

如何遍历UL中的LI项,获取特定属性,并通过$ .ajax数据传递它们

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

Here is my HTML code: 这是我的HTML代码:

<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请求:

$.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. 如果ID attr在那里,如何获取图库中每个LI的ID属性中的附件编号,并通过ajax数据以这种方式传递它们: { attached : '32,34,38,64,75' }如果有这是一个更好的方法,让我知道我想传递包含附件的列表项进行处理。 I want to avoid LI items which are empty, do not include id attr. 我想避免使用空的LI项,不包括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. 如何获取具有特色类的列表项LI {feature_img:..}并传递附件ID号(如果特色LI存在),如果没有列表项,则将features_img传递给0.所以我知道如何处理它在请求中通过PHP。

Any help is appreciated. 任何帮助表示赞赏。

Thank you. 谢谢。

There's an .map for that: 有一个.map

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. 希望这对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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