【问题标题】:Jquery each() always using last objects attributeJquery each() 总是使用最后一个对象属性
【发布时间】:2013-05-20 21:55:39
【问题描述】:

我正在尝试使用某个类遍历页面上的所有元素,然后动态设置样式颜色。 问题是它总是使用最后一个对象的颜色属性,我不知道为什么,当我记录颜色时它总是不同的? 这是我的代码:

var find= $("."+id);
find.each(function(index, element) {
    var colour = $(this).attr('colour');

    var top = $("."+id + ".top");
    var mid = $("."+id + ".middle");
    var bot = $("."+id + ".bottom");
    top.attr("style","border-bottom: 27px solid "+colour);

    mid.attr("style","background:"+colour);

    bot.attr("style","border-top: 27px solid "+colour);

});

有人知道我做错了什么吗? 非常感谢!

编辑: 这是 HTML:

<div class="hex-row">
 <a href="">
  <div class="hex ">
   <div class="top image" colour="#E1BB4E"></div>
   <div class="middle image" colour="#E1BB4E"></div>
   <div class="bottom image" colour="#E1BB4E"></div>
 </div>
</a>
<a href="">
 <div class="hex ">
  <div class="top publishing" colour="#A34F70"></div>
  <div class="middle publishing" colour="#A34F70"></div>
  <div class="bottom publishing" colour="#A34F70"></div>
</div>
</a>
</div>

问题不在于找到 div——代码针对的是正确的元素——而是将它们全部设置为相同的颜色,它应该抓取每个元素 attr('color') 并使用该颜色。

【问题讨论】:

  • $("."+id)中的id代表什么?
  • colour 不是有效的 attribute 使用 data 属性代替。您发布的代码不足以让我们为您提供帮助。显示更多。
  • Id in $("."+id) 代表“图像”或“发布”,具体取决于单击了哪个按钮。
  • @matt - 我刚刚更新了我的答案。它应该工作!

标签: jquery object attributes each attr


【解决方案1】:

似乎发生这种情况是因为您没有更改“id”变量。因此,每次迭代都为相同的元素设置新颜色,最后颜色等于“find”变量中最后一个元素的“color”属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-04
    • 2013-01-26
    • 2016-08-24
    • 2017-05-03
    • 1970-01-01
    • 2021-07-15
    • 2013-03-01
    • 2012-03-11
    相关资源
    最近更新 更多