【问题标题】:jQuery get the attr of elements into arrayjQuery将元素的属性放入数组
【发布时间】:2014-03-14 16:44:49
【问题描述】:

我有 img 和 div 的列表。我想获取 div 左侧的图像和高度的 src。这是我的代码:

<img class="img-bg" src="test.jpg">
<div class="rectangle" style="left: 252px; height: 198px;"></div>
<img class="img-bg" src="test1.jpg">
<div class="rectangle" style="left: 202px; height: 108px;"></div>


<script>
  $( document ).ready(function() {
    var arr = new Array();
    var counter = 0;
    $('.img-bg').each(function() {     

      var src = $(this).attr("src"); 
      arr[counter] = new Array(src);
        counter++;
    });
    var counter = 0;

    $('.rectangle').each(function() {

      var width = $(this).css("left");
      var height = $(this).css("height");
      arr[counter].push(width, height);
      counter++;

    });


 console.log(arr[0]);
 console.log(arr[1]);


});

这是可行的,但我想知道是否有更好的解决方案来解决我的问题。

编辑: 一切都应该在 1 个数组中。像这样的东西 ["test.jpg", "252px", "198px"] ["test1.jpg", "202px", "108px"]

【问题讨论】:

  • 不要new Array() 试试.push()
  • 你能分享想要的结果格式吗
  • 一切都应该在 1 个数组中还是在多个数组中?正如 Arun 所说,结果应该是什么?

标签: javascript jquery


【解决方案1】:

您可以使用.map().next()

$(document).ready(function () {
    var arr = $('.img-bg').map(function () {
        var $this = $(this),
            $next = $this.next('.rectangle');
        return [[$this.attr("src"), $next.css('left'), $next.css('height')]]
    }).get();

    console.log(arr[0]);
    console.log(arr[1]);
});

演示:Fiddle

【讨论】:

    【解决方案2】:

    试试

    var srcArray = [];
    var leftArray = [];
    var heigthArray = [];
    $("img").each(function () {
        srcArray.push($(this).attr("src"));
    });
    
    
    $("div").each(function () {
        leftArray.push($(this).css("left"));
        heigthArray.push($(this).css("height"));
    });
    

    【讨论】:

      【解决方案3】:

      您可以使用.map()

      var srcArr = $('.img-bg').map(function () {
          return $(this).attr("src");
      }).get();
      

      Fiddle Demo

      【讨论】:

        【解决方案4】:

        使用以下

        <script>
        
        var src1=[], left1=[], heigth1=[],counter1=0,counter2=0;
        
        $("img").each(function(){
        
          src1[counter1]=$(this).attr("src");
          counter1+=1;
         });
        
        
        $("div").each(function(){
          left1[counter2]=$(this).css("left");
          heigth1[counter2]=$(this).css("height");
            counter2+=1;
         });
        
        </script>
        

        演示=> http://jsfiddle.net/5mybd/4/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-09-13
          • 2021-01-21
          • 2011-04-13
          • 2011-07-16
          • 2019-11-25
          • 1970-01-01
          • 2013-02-04
          • 1970-01-01
          相关资源
          最近更新 更多