是否可以在数据属性中使用json内容应用CSS规则?

时间:2019-05-30 18:49:37

标签: javascript jquery html css

是否可以在div中代表ID的跨度上放置绿色背景?

//编辑。如果使它变得更容易,则只需使用div属性中的键也可以。 data-ids='["1", "2"]'甚至data-ids="1,2"。不知道有什么可能。如果没有,是否有任何聪明的JS / jQuery实现可以帮上忙?

<div data-ids='{"1":"Name A", "2":"Name B"}'>
    <span data-id="1">This should have green background</span>
    <span data-id="2">This should have green background</span>
    <span data-id="3">This should have no background</span>
</div>

虚拟代码:

div[data-ids=*] span[data-id=*] {
    background: green;
}

2 个答案:

答案 0 :(得分:1)

这将遍历div,然后遍历那些div的数据ID,然后将一个类添加到适当的子跨度

$("div[data-ids]").each(function(){
    let obj = $(this);
    $.each($(this).data("ids"),function(k,v){
      $(obj).find("span[data-id='" + k + "']").addClass("highlight");
    });
});
.highlight{
    background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-ids='{"1":"Name A", "2":"Name B"}'>
    <span data-id="1">This should have green background</span>
    <span data-id="2">This should have green background</span>
    <span data-id="3">This should have no background</span>
</div>

答案 1 :(得分:1)

您不能使用CSS动态设置样式。如果必须这样做,则需要手动输入所有可能性。

例如,如果您需要<span>id == 1的{​​{1}}为绿色背景,则需要这样编写CSS:

id == 2
div[data-ids] span[data-id="1"],
div[data-ids] span[data-id="2"] {
  background: #0f0;
}

您必须使用JS或jQuery来做您需要做的事情:

JavaScript(为简化起见,ES6)-请参阅注释以获取解释

<div data-ids='{"1":"Name A", "2":"Name B"}'>
  <span data-id="1">This should have green background</span>
  <span data-id="2">This should have green background</span>
  <span data-id="3">This should have no background</span>
</div>
// Get the div with `data-ids` attribute
const div = document.querySelector('div[data-ids]');

// Get the data in `data-ids`
const ids = div.dataset.ids;

// Parse the string data into Object
const data = JSON.parse(ids);

// Loop over the keys (id) of the data
// Selecting matching span to style them.
for (const id in data){
  const spans = document.querySelectorAll(`span[data-id="${id}"]`);
  spans.forEach(span => {
    span.style.background = '#0f0';
  });
}

jQuery(为简化起见,ES6)-请参阅注释以获取解释

<div data-ids='{"1":"Name A", "2":"Name B"}'>
  <span data-id="1">This should have green background</span>
  <span data-id="2">This should have green background</span>
  <span data-id="3">This should have no background</span>
</div>
// Get the div with `data-ids` attribute
const $div = $('div[data-ids]');

// Get the `ids` from attribute.
// jQuery automatically parse string data into JSON if valid.
const data = $div.data('ids');

// Loops through the ids and set matching span background color.
$.each(data, function(id){
  $(`span[data-id="${id}"]`).css('background', '#0f0');
});