[英]Changing CSS using JQuery for multiple, dynamically created divs (unknown div IDs)
I am creating a bunch of color swatches from an array using PHP. 我正在使用PHP从数组中创建一堆颜色样本。
Here is the PHP code (I've removed some of the colors from the array, to make the code shorter, in practice there are many more). 这是PHP代码(我从数组中删除了一些颜色,以使代码更短,实际上还有更多颜色)。
$colors = array(
"Light Blue"=>"198,248,253",
"Medium Blue"=>"112,204,246",
"Blue"=>"84,140,242",
"Dark Blue"=>"52,55,199",
"Dark Green"=>"53,172,58",
"Light Green"=>"191,235,104"
);
echo "<label>Color:</label>";
foreach ($colors as $colorName => $colorCode) {
echo "<div style='background-color:rgb(".$colorCode.");' class='swatch' id='".str_replace(" ","_",$colorName)."'></div>";
}
I would like, when the user selects (clicks) a swatch, a css border is added to highlight the user's selection. 我想,当用户选择(单击)一个色板时,将添加一个CSS边框以突出显示用户的选择。
I have tried the following JQuery, but can't seem to get it working. 我尝试了以下JQuery,但似乎无法正常工作。
$(document).ready(function() {
$(document).on('click', 'div', function () {
$(this.id).css('border','solid 1px black');
});
}); });
I'm sure it is something rather simple, simply down to my lack of experience with JQuery. 我确信这很简单,只是由于我缺乏JQuery经验。 Any help appreciated.
任何帮助表示赞赏。 Thanks,
谢谢,
Dingo Bruce 丁戈·布鲁斯
You know you have a class
given to each dynamically created element
. 您知道每个动态创建的
element
都有一个class
。 So just use event delegation
and add css
to clicked class
rather say element
as follows: 因此,只需使用
event delegation
并将css
添加到单击的class
而不要说出如下element
:
$(document).on('click','.swatch',function(){
$(this).css('border','solid 1px black'); //$(this) refers to current element here
});
As per @Anders comment if you want to remove border from all other divs
with class swatch
and want to keep only on the current clicked item below will be the piece of code which helps you to achieve the same. 根据@Anders的评论,如果您想从所有其他
divs
删除带有swatch
类的边框,并且只想保留下面当前单击的项目,那么这段代码将帮助您实现这一目标。
$(document).on('click','.swatch',function(){
$('.swatch').css('border','0px');
//if you don't have any extra inline styling then you can directly remove your
//style attribute with $('.swatch').removeAttr('style'); Use either of one
$(this).css('border','solid 1px black'); //$(this) refers to current element here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.