繁体   English   中英

如何获取元素的ID并将其作为CSS属性应用?

[英]How to get the id of an element and apply it as a CSS property?

 <ul> <li> <span class="circle" id="beige"></span> <span>Beige</span> </li> <li> <span class="circle" id="black"></span> <span>Black</span> </li> <li> <span class="circle" id="blue"></span> <span>Blue</span> </li> </ul> 

我想从圆形类中选择ID,并将该ID作为背景色应用于同一类。

我的jQuery是:

$('span.circle').each(function (index, element) {
    $(element).css({
        'background-color': $('.circle').attr('id')
    });
});

但是,当我这样做时,它仅选择第一个span元素的id并将该id颜色应用于同一类的所有其他span。 知道如何选择不同的ID,以便在不同跨度上具有不同的背景颜色吗?

提前致谢

使用css()方法的匿名函数:

$('.circle').css('background-color', function () {
  return this.id;
});

该方法本身(与大多数jQuery方法一样)在调用它的集合上进行迭代,在匿名函数中, this指向迭代在其上移动的特定元素。

顺便说一句,原因是:

$('.circle').attr('id');

不能正常工作是因为每次您重新选择整个集合,然后调用attr()方法的getter版本时,该方法在集合上调用时仅返回该集合的第一个元素的结果。

而且,顺便说一句,当您有权访问DOM节点时,请勿使用jQuery检索id

$(DOMElementReference).attr('id');

和:

$(DOMElementReference).prop('id');

只是以下产品的昂贵版本:

DOMElementReference.id;

参考文献:

尝试在each的上下文中引用元素:

$('span.circle').each(function(index, element) {
    $(element).css({
        'background-color': $(element).attr('id');
    });
});

我正在使用vars使其更易于理解。 $(this)将在每次迭代中引用当前元素。 我将其分配给'$ this'变量,因此我们不会多次运行选择器。

$('span.circle').each(function() {
    var $this = $(this),
    elementId = $this.attr('id');
    $this.css({'background-color': elementId});
});

这是有效的代码 HTML中也存在错误,跨度未正确放置

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title>Drag Me</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    </head>

    <body>
        <ul>
            <li> <span class="circle" id="beige">
  <span>Beige</span>
</span>
            </li>
            <li> <span class="circle" id="black">
  <span>Black</span>
</span>
            </li>
            <li> <span class="circle" id="blue">
  <span>Blue</span>
</span>
            </li>
        </ul>
        <script>
            $(document).ready(function() {

                $('span.circle').each(function(index, element) {
                    console.log($(element).attr('id'));
                    $(element).css(
                        'color', $(element).attr('id'));
                });
            });
        </script>
    </body>

</html>

代替:

$('.circle').attr('id')

是:

element.id

像这样的东西:

$('span.circle').each(function(index, element) {
   $(element.id).css('background-color', element.id);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM