迭代数据属性jQuery

时间:2014-10-21 11:17:25

标签: javascript jquery

我对以下内容的反应并不是很远,所以希望有人能解释一下该做什么,以便我能理解这个过程。

我有这个HTML

<span data-credit-name="Name_1"><strong>1</strong> Name 1</span><br />
<span data-credit-name="Name_2"><strong>2</strong> Name 2</span><br />
<span data-credit-name="Name_3"><strong>1</strong> Name 3</span><br />
<span data-credit-name="Name_4"><strong>1</strong> Name 4</span><br />
<span data-credit-name="Name_5"><strong>3</strong> Name 5</span><br />
<span data-credit-name="Name_6"><strong>1</strong >Name 6</span><br />
<span data-credit-name="Name_7"><strong>4</strong> Name 7</span><br />

我想要做的是遍历每个范围并收集其数据信用名称和强标记内的值,并创建一个看起来像这样的js对象

var credit = {Name_1:"1", Name_2:"2", Name_3:"3"};

我试过这个以获得第一个但返回空字符串

var credit = $('span[data-credit-name]:first').text();
console.log(credit);

任何帮助将不胜感激

谢谢

4 个答案:

答案 0 :(得分:4)

这应该可以解决问题......

var credit = {};

$("span[data-credit-name]").each(function() {
    credit[$(this).data("credit-name")] = $(this).find("strong").text();
});

jsfiddle例子......

http://jsfiddle.net/t9bthjg4/

答案 1 :(得分:3)

要获取数据属性,您应该使用jQuery .data()方法。您可以这样迭代:

var credit = {};

$("span[data-credit-name]").each(function(){

   var key = $(this).data("credit-name");

   var value = $(this).find("strong").text();

  credit[key] = value;

});

var credit = {};

$("span").each(function(){
  
   var key = $(this).data("credit-name");
 
  var value = $(this).find("strong").text();
  
  credit[key] = value;

});

console.log(credit);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-credit-name="Name_1"><strong>1</strong> Name 1</span><br />
<span data-credit-name="Name_2"><strong>2</strong> Name 2</span><br />
<span data-credit-name="Name_3"><strong>1</strong> Name 3</span><br />
<span data-credit-name="Name_4"><strong>1</strong> Name 4</span><br />
<span data-credit-name="Name_5"><strong>3</strong> Name 5</span><br />
<span data-credit-name="Name_6"><strong>1</strong >Name 6</span><br />
<span data-credit-name="Name_7"><strong>4</strong> Name 7</span><br />

答案 2 :(得分:1)

您可以map所需的值,并使用get()从jQuery对象中解包结果。

最重要的是:

var result = $('span[data-credit-name]').map(function(i, el){

var ret = {},
    $span = $(el),
    creditName = $span.data('credit-name');

    ret[creditName] = ++i; 
    return ret; 

}).get();

console.log(result);

http://jsfiddle.net/5d09bo4c/2/

(根据您在问题中的最新HTML更改)

答案 3 :(得分:1)

var out = {};
$.each($('span'), function (i, el) {
  var $this = $(this);
  var strong = $this.find('strong').html();
  var data = $this.data('credit-name');
  out[data] = strong;
});

DEMO