JQuery 从列表中获取所有数据属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17346640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:51:23  来源:igfitidea点击:

JQuery get all data attributes from a list

javascriptjqueryjquery-selectors

提问by Sideshow

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>

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

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

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

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

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

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

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 :)

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

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

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

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.

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

回答by tymeJV

You can use .mapto return an array:

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

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

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

Demo: http://jsfiddle.net/RPpXu/

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

回答by YD1m

Use this:

用这个:

var array = [];

$('li.list').each(function() {
  array.push($(this).data('id'));
})

var joined = array.join('|');

回答by James Harrington

Not an answer to your question but this is what i ended up on this page in search for and though it would help someone else :-)

不是你问题的答案,但这就是我在这个页面上搜索的结果,虽然它会帮助其他人:-)

var arrayOfObj = $('input').map(function() {

  return {
            name : $(this).attr('name'),
            data : $(this).data('options'),
            value : $(this).val(),
            id : $(this).attr('id')
         }

}).get();
console.log(arrayOfObj)

This returns an array of objects that mimics the input
Cheers!

这将返回一个模仿输入的对象数组
Cheers!