JQuery 从列表中获取所有数据属性 [英] JQuery get all data attributes from a list

查看:59
本文介绍了JQuery 从列表中获取所有数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的动态生成的列表,每个列表都具有相同的类标识符和类似于以下代码的数据属性:

I have a long dynamically generated list each with the same class identifier and a data attribute similar to the code below:

<ul>
    <li class="list" data-id="123">One</li>
    <li class="list" data-id="124">Two</li>
    <li class="list" data-id="125">Three</li>
    <li class="list" data-id="126">Four</li>
    .....etc
</ul>

我想要实现的是获取所有 data-id 值并将它们格式化如下:

what I am trying to achieve is to get all the data-id values and format them in as follows:

123|124|125|126....etc

然后这将通过 ajax 传递到页面,并检查该 ID 是否存在于数据库中.

this would be then passed to a page via ajax and the id's checked for existence in a database.

var delimited_data="";
$('.list').each(function(){
    delimited_data+=$(this).data('id')+"|";
});
console.log(delimited_data);

我问这个问题的原因是我正在开发一个实时系统,该系统会在 10 分钟后自动将列表列中的项目部署给不同的用户.我只需要确保代码以正确的方式运行:)

The reason I am asking this question is that I am working on a live system that automatically deploys items in the list columns to different users after 10 mins. I just need to be sure that the code is going the right way :)

我还需要检查页面上是否没有 .list 类(即 - 无法进行查询)delimited_data 是否将完全为空我很确定会这样.

I also need to check that is there are no .list classes on the page (ie - no way to do the query) whether delimited_data will be totally empty which I am pretty sure it would be.

在这种情况下,有没有比使用 .each() 更好的方法,因为我发现上面的函数每 30 秒运行一次可能会相当慢.

Is there a better way than using .each() in this case as I find it can be rather slow baring in mind that the above function will be run every 30 seconds.

推荐答案

你可以使用 .map 返回一个数组:

You can use .map to return an array:

var dataList = $(".list").map(function() {
    return $(this).data("id");
}).get();

console.log(dataList.join("|"));

演示:http://jsfiddle.net/RPpXu/

这篇关于JQuery 从列表中获取所有数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆