繁体   English   中英

如何使用jQuery从li标签获取ID?

[英]How can i get Ids from li tags using jQuery?

这是html代码:

<ul id="sortable">
    <li id="attachments[183]"></li>
    <li id="attachments[196]"></li>
    <li id="attachments[145]"></li>
    <li id="attachments[545]"></li>
</ul>

这是JavaScript / jQuery代码:

var query = {
    'action'  : 'save-attachment-order',
    'nonce'   : '8cb16e3927',
    'post_id' :  89,
}

我想获取li ID并使其像这样变

var query = {
    'action'  : 'save-attachment-order',
    'nonce'   : '8cb16e3927',
    'post_id' :  89,
    'attachments[183]' : 2,
    'attachments[196]' : 3,
    'attachments[145]' : 1,
    'attachments[545]' : 4
}

从这个对象开始:

var query = {
    'action'  : 'save-attachment-order',
    'nonce'   : '8cb16e3927',
    'post_id' :  89,
}

您可以使用以下方法将id添加为新属性:

$("#sortable li").each(function(){
    query[this.id] = 0; // not sure where you're getting the values from!
});

既然您已经解释了值应该表示顺序,那么您可能要改用它(假设jQuery UI):

var order = $( "#sortable" ).sortable( "toArray" );
for(var i=0; i<order.length; i++) {
    query[order[i]] = i+1;
}

Alnitak的答案也应该起作用,因为无论如何,列表项都是按顺序排列的。

var ids = [];

$('li').each(function() {
  ids.push($(this).attr('id'));
});

这会将ID添加到query ,其值是元素在列表中的相对位置:

$('#sortable > li').each(function(ix) {
    query[this.id] = ix + 1;
});

参见http://jsfiddle.net/alnitak/qddc5/

var ids = $("#sortable li").map(function(){
           return this.id;
          }).get();

这将获取所有li id作为数组。

尝试这个

object.property = value;

所以你的代码成为

$('#sortable li').each(function() {
  query[$(this).attr('id')]= 'vaule u want';
});

暂无
暂无

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

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