【问题标题】:how to match obj with class name with jquery如何将obj与类名与jquery匹配
【发布时间】:2021-10-22 04:22:15
【问题描述】:

在这种情况下,我将 div 描述为一个带有方形和圆形孔的盒子。

盒子:

<div id="box">
  <div class="square"></div>
  <div class="circle"></div>
</div>

然后,我有一个对象要放在一个盒子里。

物体形状:

var string = [ 
    {shape: 'square', item: 'item1'},
    {shape: 'square', item: 'item2'},
    {shape: 'circle', item: 'item3'}
];

那我想按照同孔的形状把物体放进盒子里。

$.each(string, function(key, e) {
  /* if inside the div box has several names equal to the value obj */
  if ($('#box').find().attr('class') == e.shape) {

    var data = "<span>" + e.item + "</span>"
    $(data).appendTo(e.shape);

    /* append value item to 
    each div with same name */
  }
});

但是这段代码对我不起作用。 我想要的结果是这样的

<div id="box">
  <div class="square">
   <span>item1</span>
   <span>item2</span>
  </div>
  <div class="circle">
    <span>item3</span>
  </div>
</div>

【问题讨论】:

    标签: jquery arrays object


    【解决方案1】:

    考虑以下内容。

    $(function() {
      var string = [{
          shape: 'square',
          item: 'item1'
        },
        {
          shape: 'square',
          item: 'item2'
        },
        {
          shape: 'circle',
          item: 'item3'
        }
      ];
    
      $.each(string, function(i, s) {
        $("#box ." + s.shape).append("<span class='item'>" + s.item + "</span>");
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="box">
      <div class="square"></div>
      <div class="circle"></div>
    </div>

    这使用类选择器来选择形状:$("." + s.shape)。这将连接字符串,因此您以 $(".square") 为例。一旦你选择了合适的元素,你就可以追加它。

    生成的 HTML

    <div id="box">
      <div class="square">
        <span class="item">item1</span>
        <span class="item">item2</span>
      </div>
      <div class="circle">
        <span class="item">item3</span>
      </div>
    </div>
    

    【讨论】:

      【解决方案2】:

      这可以更简单一点,也许通过使用形状作为一个类:

      var newContent = [{
          shape: 'square',
          item: 'item1'
        },
        {
          shape: 'square',
          item: 'item2'
        },
        {
          shape: 'circle',
          item: 'item3'
        }
      ];
      
      $.each(newContent, function(index, val) {
        console.log(index, val);
        $('#box')
          .find("." + val.shape)
          .append("<span class='item-thing'>" + val.item + "</span>")
      });
      .item-thing {
        border: 1px solid lime;
        margin-right: 1rem;
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <div id="box">
        <div class="square"></div>
        <div class="circle"></div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-02
        • 2017-11-06
        • 1970-01-01
        • 2017-04-12
        • 2015-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多