jQuery:从data属性设置子元素颜色

3
有什么办法可以让它正常工作吗?
$("div[data-color]").each(function() {
    $(this).children('p').css('color', function () {
        return $(this).data('color')
    });
});

结构看起来像这样

<div data-color="#ff0000"><p>text that needs right color</p></div>

如果这是您正在使用的所有相关标记,则只需设置DIV颜色,因为该属性将继承给所有后代 https://jsfiddle.net/5cn0v7mw/ - A. Wolff
3个回答

5

不需要在其中使用回调函数,this指的是p而不是div

$("div[data-color]").each(function() {
    $(this).children('p').css('color', $(this).data('color'))
});

$("div[data-color]").each(function() {
  $(this).children('p').css('color', $(this).data('color'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-color="#ff0000">
  <p>text that needs right color</p>
</div>

或者使用回调函数来完成:

$("div[data-color] > p").css('color',function(){
    return $(this).parent().data('color');
    // or return this.parentNode.dataset.color
});

$("div[data-color] > p").css('color', function() {
  return $(this).parent().data('color');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-color="#ff0000">
  <p>text that needs right color</p>
</div>


使用纯JavaScript,使用querySelectorAllArray#forEach方法。

Array.from(document.querySelectorAll("div[data-color] > p")).forEach(function(ele) {
  ele.style.color = ele.parentNode.dataset.color;
});

Array.from(document.querySelectorAll("div[data-color] > p")).forEach(function(ele) {
  ele.style.color = ele.parentNode.dataset.color;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-color="#ff0000">
  <p>text that needs right color</p>
</div>


2
在CSS回调函数中,this 指的是 p 元素而不是 div 元素。您可以使用 each 回调函数的第二个参数。
$("div[data-color]").each(function(i, el) {
    $(this).children('p').css('color', function () {
        return $(el).data('color')
    });
});

另一个选项是:
$("div[data-color] > p").css('color', function () {
    return this.parentNode.getAttribute('data-color');
});

1

是的,我也意识到了。这个可以工作,但你的也行。

$("div[data-color]").each(function() {
    $(this).find('p').css('color', $(this).attr('data-color'));
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接