使用Javascript编写HTML以引用属性数据
我想使用带有javascript的锚定标记的属性向相邻元素添加一个类: HTML: 我最终在寻找:使用Javascript编写HTML以引用属性数据,javascript,html,Javascript,Html,我想使用带有javascript的锚定标记的属性向相邻元素添加一个类: HTML: 我最终在寻找: <li><a href="#" class="swatchButton" data-color="blk"><span class="blk"></span>Black</a></li> 是否需要使用forEach()创建某种数组 谢谢! 在jquery中使用each() $(document).ready(functi
<li><a href="#" class="swatchButton" data-color="blk"><span class="blk"></span>Black</a></li>
是否需要使用forEach()
创建某种数组
谢谢!
在jquery中使用each()
$(document).ready(function(){
$(".swatchButton").each(function() {
var swatchColor = $(this).data('color');
$(this).find('span').addClass(swatchColor);
});
});
演示:在jquery中使用each()
$(document).ready(function(){
$(".swatchButton").each(function() {
var swatchColor = $(this).data('color');
$(this).find('span').addClass(swatchColor);
});
});
演示:您的代码
var-swatchColor=$(“.swatchButton”).data('color')
将返回classswatchButton
和$(“.swatchButton”).find('span').addClass(swatchColor)的第一个元素的数据颜色
将该值分配给每个span
元素,该元素是类为swatchButton
的元素的后代
您需要分别为每个跨度设置颜色
$('.swatchButton span').addClass(function(){
return this.parentNode.dataset.color;
});
演示:
或
演示:您的代码var-swatchColor=$(“.swatchButton”).data('color')
将返回classswatchButton
和$(“.swatchButton”).find('span').addClass(swatchColor)的第一个元素的数据颜色
将该值分配给每个span
元素,该元素是类为swatchButton
的元素的后代
您需要分别为每个跨度设置颜色
$('.swatchButton span').addClass(function(){
return this.parentNode.dataset.color;
});
演示:
或
演示:效果很好,我只需将addClass(swatchColor)
替换为`addClass(color)就可以了,谢谢!这真是太棒了,我只需要用'addClass(color)替换addClass(swatchColor)
,效果很好,谢谢!我知道这是一个更优雅的解决方案,但我花了一分钟的时间来理解。您如何描述这两种解决方案之间的差异?i、 e.描述使用$(this.parent)(
与this.parentNode
@user27068之间的区别一个使用jQuery方法($(this.parent)(
),而另一个只使用vanila脚本(this.parentNode
),因此基于vanila脚本的解决方案只能在现代浏览器上工作(在IEGreat中不起作用,谢谢您的回复!我还发现了这个aka$(this)->我认为这是一个更优雅的解决方案,但我需要花一分钟的时间来理解。您如何描述这两个解决方案之间的区别?即,描述使用$(this).parent)之间的区别()
vsthis.parentNode
@user27068其中一个使用jQuery方法($(this.parent)(
),而另一个只使用vanila脚本(this.parentNode
),因此基于vanila脚本的解决方案只能在现代浏览器上工作(在IEGreat中不起作用,感谢您的回复!我还发现了这个aka$(this)->
$('.swatchButton span').addClass(function(){
return $(this).parent().data('color');
});