javascript - 将两个数组传递给函数,使用数据来启动按钮按下。Javascript
问题描述
我有一个项目列表和一个颜色列表。我正在尝试创建一个干净的功能,您可以单击代表颜色的按钮($colorCount)并更改项目的颜色($itemList)。
我试图将两个数组传递给一个函数来启动按钮按下,当我记录代码时,数组正在显示,但是当我达到目标时什么都没有发生。
$itemList = ["RSST2","CM102"];
$colorCount = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
colorDisplay($itemList, $colorCount);
function colorDisplay($c, $b) {
console.log ($c);
console.log ($b);
$("#target-"+$c+"-"+$b).click(function(){
console.log ("button clicked " + $b);
$("#"+$c+"-"+$b).addClass("active-img");
$("#"+$c+"-"+$b).removeClass("waiting-img");
$("#"+$c+"-"+$b).siblings().addClass("waiting-img");
});
}
我的 HTML 是这样的......我正在使用 wordpress 和 ACF 转发器字段
<div class="prod-img-cont">
<?$z=0;
if( have_rows('additional_colors' , $product_item->ID) ):
while ( have_rows('additional_colors', $product_item->ID) ) : the_row();
$color_images = get_sub_field('color_images', $product_item->ID);
?>
<img class="<?php if( ($z) == "0" ){
echo "active-img";
} else {
echo "waiting-img";
}?>" id="<?=$product_name;?>-<?=$z;?>" src="<?=$color_images;?>">
<?
$z++;
endwhile;
else :
// no rows found
endif;?>
</div>
<div class="product-list-item-right">
<div class="additional-colors">
<h2>Available Colors:</h2>
<div class="color-grid">
<?$z=0;
if( have_rows('additional_colors' , $product_item->ID) ):
while ( have_rows('additional_colors', $product_item->ID) ) : the_row();
$color_choice = get_sub_field('color_sample', $product_item->ID);
?>
<button class="color-choice" id="target-<?=$product_name;?>-<?=$z;?>" style="background-color:<?=$color_choice;?>"></button>
<?
$z++;
endwhile;
else :
// no rows found
endif;?>
</div>
</div>
</div>
所以 $itemList 数组是指 PHP 中的 $product_name ,我正在遍历行以获取 $colorCount 数字
我觉得我的思维过程是正确的,但我缺少一些基本的东西,这些东西没有给我我需要的输出。
解决方案
问题在于您定义选择器的方式 - 正如其他人已经提到的,当您尝试将字符串与数组连接时,JavaScript 会将数组转换为以逗号分隔的条目列表,如下所示:
"abc-" + [1,2,3] ==> "abc-1,2,3"
这不是你想要做的。在这种情况下,您可以尝试从事件冒泡中受益(单击事件“冒泡”DOM)并将侦听器附加到顶部容器(#product-list-item-right)。在该侦听器中,您将检查原始事件目标,如果它以“#target-”为开头,那么您将解析出颜色代码和产品 ID,然后选择/操作适当的元素
希望有帮助!
推荐阅读
- excel - 如何解决公式错误在宏中解决
- asp.net - 是否可以对所有 Web 项目使用 razor 类库?
- python - 在 Pandas Dataframes 中跨多列计算特定单词,按列分组输出
- mysql - JSON_ARRAY_APPEND 与 NodeJs 续集
- android - dagger2 中的@Provide 和@Inject 有什么区别?
- docker - 容器(运行在本地主机上)如何访问远程主机上运行的服务,这些服务是端口转发到本地主机的
- python - AttributeError:模块“tensorflow.compat.v2”没有属性“depth_to_space”
- java - 反转时Java比较器不适用于通用类型
- html - 一些元素没有在 HTML 中排列
- java - 当我包含大型资源文件并构建/运行 JAR 文件时,为什么我的 Springboot Springdoc /swagger-ui.html 端点返回 404?