Featured post
javascript - JQuery wrong ID in an inner click -
i'm trying make colorpicker. got few colorcubes class colorcube. when clicking, opens colorpicker few list items have different color. when clicking on list items should return de color/text de colorcube.
the first colorpick after document ready works. after doesnt work properly, because remembers al previous colorcube id's al other cube's change :(
is there way clear cache or that?
$('.colorcube').click(function() { var colorcubeid = $(this).attr("id"); $('#choicecolor').show(); $(".li_color").click(function() { var colorid = "#" + this.id; var colorli = $(colorid).text(); $('#' + colorcubeid).text(colorli); $('#' + colorcubeid).css({ 'background-color': '' + colorli + '' }); $('#choicecolor').hide(); savecolor(); }); });
you're assigning redundant click
event handlers every click on colorcube
. should assign handlers once.
it seems you're doing in order reference id of colorcube
clicked. use variable instead track clicked.
var $currentcube, $choicecolor = $('#choicecolor'); $('.colorcube').click(function() { $currentcube = $(this); $choicecolor.show(); }); $(".li_color").click(function() { var colorli = $(this).text(); $currentcube.text(colorli) .css({ 'background-color': colorli }); $choicecolor.hide(); savecolor(); });
i made number of changes well.
instead of referencing id of current color cube, i'm referencing actual element wrapped in jquery object, can call methods on directly.
this code:
var colorid = "#" + this.id; var colorli = $(colorid).text();
...is more complex needed, since can do:
var colorli = $(this).text();
...where this
<li>
clicked.
you don't need:
'' + colorli + ''
because colorli
string. do
.css({ 'background-color': colorli })
as @Šime vidas noted, should cache $('#choicecolor');
you're not selecting dom.
var $currentcube, $choicecolor = $('#choicecolor');
i used chaining on line. jquery don't need separate function calls against same jquery object. can chained together.
$currentcube.text(colorli) .css({ 'background-color': colorli });
- Get link
- X
- Other Apps
Comments
Post a Comment