【问题标题】:iterate through data from span tags遍历 span 标签中的数据
【发布时间】:2013-07-14 00:22:09
【问题描述】:

我正在尝试从我拥有的几个跨度标签中选择数据,第一个标签记录在控制台中,但之后的值为“未定义”

生成span标签的erb:

<%= image.connections.each do |conn| %>
    <span class="connection" data-pos-x="<%= conn.pos_x %>"></span>
    <span class="connection" data-pos-y="<%= conn.pos_y %>"></span>
<% end %>

我的 jQuery 是:

console.log($("span").attr('data-pos-x'));
console.log($("span").attr('data-pos-y'));

erb 生成了多个 x-y 坐标,因此我需要一种方法来遍历所有坐标,但我不知道该怎么做。

【问题讨论】:

    标签: jquery for-loop iteration html


    【解决方案1】:
    $("span.connection").each(function() {
        var xpos = $(this).data('pos-x');
        var ypos = $(this).data('pos-y');
        if (xpos !== undefined) {
            console.log("X: "+xpos);
        }
        if (ypos !== undefined) {
            console.log("Y: "+ypos);
        }
    });
    

    【讨论】:

    • 您先生是圣人。谢谢!
    【解决方案2】:

    如果你只想使用元素进行迭代,你可以

    $(".connection").each(function(){
        var data = $(this).data();
        console.log(data);
    });
    

    如果你需要数组中的数据

    var dataPoints = $.map($(".connection"), function(index, element){
        var data = $(element).data();
        console.log(data);
        return data;
    });
    

    【讨论】:

      【解决方案3】:

      将您的代码封装在DOM Ready event handler 中,然后使用$.each 进行迭代

      $(function() {
      
         $('span.connection').each(function() {
            // cache the current span
            var $this = $(this),
                xCord = $this.data('pos-x') !== undefined ? $this.data('pos-x') : '--',
                yCord = $this.data('pos-y') !== undefined ? $this.data('pos-y') : '--',
      
            console.log('X-cord : ' + xCord + ' :: ' + 'Y-cord : ' + yCord)
      
         });
      

      });

      -

      $("span").attr('data-pos-x') 也有效.. 但最好使用 检索自定义属性的数据方法。

      【讨论】:

      • 请注意,每个跨度都有一个 X 坐标或一个 Y 坐标,但不是两者都有。
      猜你喜欢
      • 2023-03-17
      • 2015-01-11
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      相关资源
      最近更新 更多