使用jQuery迭代每个div属性? [英] iterate each div attribute using jQuery?

查看:68
本文介绍了使用jQuery迭代每个div属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取每个div的rgb和索引值.在控制台中,我可以正确获取所有内容(索引和B 每个div的背景颜色).尝试将每个值添加到每个 div 中的一个 p 中,我只有每个 div 重复的最后一个值:蓝色的十六进制和数字5, 我该怎么解决?

I'm trying to get the rgb and index value of each div. In the console I get everything correctly (index and B background color for each div). Trying to add each value to a p in every div I have only the last value repeated for each div: the hex of blue and the number 5. How can I solve?

.red {
    background-color:red; 
}.orange {
    background-color:orange; 
}
.yellow {
    background-color:yellow; 
}
.purple {
    background-color:purple; 
}
.blue {
    background-color:blue; 
}
<div class="red"><p></p></div>
<div class="orange"><p></p></div>
<div class="yellow"><p></p></div>
<div class="purple"><p></p></div>
<div class="blue"><p></p></div>

$('div').each(function(index) {
  var x = $(this).css('background-color');
  $("div p").text(index+x);
  console.log(index+x);
});

  • [日志] rgb(255,0,0)#ff0000
  • [日志] rgb(255,165,0)#ffa500
  • [日志] rgb(255,255,0)#ffff00
  • [Log] rgb(128,0,128)#800080
  • [日志] rgb(0,0,255)#0000ff
    • [Log] rgb(255, 0, 0) #ff0000
    • [Log] rgb(255, 165, 0) #ffa500
    • [Log] rgb(255, 255, 0) #ffff00
    • [Log] rgb(128, 0, 128) #800080
    • [Log] rgb(0, 0, 255) #0000ff
    • 推荐答案

      更改以下内容...

      $("div p").text(index+x);
      

      致...

      $(this).find("p").text(index+x);
      

      目前,您将再次找到所有<div>个元素,并在每个元素中填充<p> ...这就是为什么您看到所有元素的最终值

      As currently you are finding ALL <div> elements again, and populating the <p> in each one... that is why you're seeing the final value across all

      $('div').each(function(index) {
        var x = $(this).css('background-color');
        $(this).find("p").text(index+x);
        console.log(index+x);
      });

      .red {
          background-color:red; 
      }.orange {
          background-color:orange; 
      }
      .yellow {
          background-color:yellow; 
      }
      .purple {
          background-color:purple; 
      }
      .blue {
          background-color:blue; 
      }

      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      
      <div class="red"><p></p></div>
      <div class="orange"><p></p></div>
      <div class="yellow"><p></p></div>
      <div class="purple"><p></p></div>
      <div class="blue"><p></p></div>

      这篇关于使用jQuery迭代每个div属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆