gpt4 book ai didi

javascript - 使用点击功能检查多个div中的数据属性值

转载 作者:太空宇宙 更新时间:2023-11-03 22:22:36 24 4
gpt4 key购买 nike

我正在尝试获取一组选定的 div,以根据按钮数据属性中的数据集更改背景颜色。

我已经做了一些挖掘,但我对如何针对 div 中的标题和按钮的数据属性中的数据传递条件感到困惑。

我知道我可能必须 .split() 按钮中的数据,因为每个按钮都有多个数据属性。但是,获取该信息并再次检查 div 集是我认为我被挂断的地方。

这是我目前所拥有的:

Codepen 链接: https://codepen.io/ultraloveninja/pen/bmvOYB

HTML:

<section class="state-group">
<div class="state" title="Illinois">
<h2>Illinois</h2>
</div>
<div class="state" title="New Hampshire">
<h2>New Hampshire</h2>
</div>
<div class="state" title="Washington">
<h2>Washington</h2>
</div>
<div class="state" title="North Dakota">
<h2>North Dakota</h2>
</div>
<div class="state" title="South Dakota">
<h2>South Dakota</h2>
</div>
<div class="state" title="Wisconsin">
<h2>Wisconsin</h2>
</div>
</section>

<section class="btn-group">
<a data-state='New Hampshire,Illinois,Wisconsin' class="region region-one" href="">Region 1</a>
<a data-state='Illinois,Washington,North Dakota' class="region region-two" href="">Region 2</a>
<a data-state='Washington,North Dakota,South Dakota' class="region region-three" href="">Region 3</a>
</section>

JS:

var $region = $('.region').data("state");
var $single = $region.split(',');

$(".region").on("click", function(e) {
$(".state-group div").each(function() {
var $state = $(this).attr("title");
if ($state == $single ) {
$(this).css('background-color','blue')
}
});
e.preventDefault();
});

基本上,一旦您单击按钮,它就会检查您单击的按钮的数据,找到 div 的标题(在本例中为状态),如果匹配,则将这些特定 div 的背景设为蓝色。

同样,不确定我是否以正确的方式处理此问题,或者我是否需要从 div 获取数据并将其存储在变量中。希望这是有道理的。

最佳答案

您应该从单击的按钮获取状态,而不是在加载 js 时获取状态。这样你就会有基于点击按钮的状态。

$(".region").on("click", function(e) {
//Below line is important; Otherwise it won't work for other buttons.
var $single = $(this).data("state").split(",");

$(".state-group div").each(function() {
var $state = $(this).attr("title");
if ($single.indexOf($state) > -1) {
$(this).css('background-color','blue');
}else{
$(this).css('background-color','#ccc');
}
});
e.preventDefault();
});

https://codepen.io/anon/pen/PyRgEZ

关于javascript - 使用点击功能检查多个div中的数据属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52878533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com