javascript - jQuery click event on wrong element created via loop -
i'm trying dynamically create portfolio parts website in jquery can add stuff later ease through database. i've got working, except listener redirects last listener created, seems. no matter header click, opens last option, not 1 clicked. here's code have:
var portfolio_array = <?php echo json_encode($globals["portfolio_array"]); ?>; (var = portfolio_length - 1; >= 0; i--) { var project_name = portfolio_array[i]["name"]; var project_tag = portfolio_array[i]["tag"]; var project_description = portfolio_array[i]["description"]; var project_year = portfolio_array[i]["year"]; var project_image = portfolio_array[i]["image"]; $("projects").append("<project class = " + project_tag + ">"); $("."+project_tag).append("<br><project_header class = project-header>" + project_name + "</project_header>"); $("."+project_tag).append("<br><project-content class = slideable></project-content>"); $("."+project_tag).children(".slideable").append("<project_description class = project-desc>"+project_description+"</project_description>"); $("."+project_tag).children(".slideable").append("<br><project_image class = project-image>"+project_image+"</project_image>"); //<img src="pic_mountain.jpg" alt="mountain view" style="width:304px;height:228px;"> $("."+project_tag).children(".slideable").hide(1000); //alert("added click listener tag " + project_tag); $("."+project_tag).children(".project-header").click(function(event){ $("."+project_tag).children(".slideable").slidetoggle(400); //alert("clicked " + project_tag); }); };
i've tried debugging through alerts, couldn't find wrong other click alert pointing last project created. alert before creation of event giving me correct project names.
anyone see what's wrong this? i'm still kind of new this, if there might stupid mistake somewhere in there don't know of yet...
this classic mistake, problem click handlers using same project_tag
, , value changes time handler activated.
you can fix @tahirahmed suggested using this
of handler (which dom element clicked). prefered since can bind same click handler many elements @ once , use this
differentiate.
alternatively can use closure bind handler function current value (at time function bound).
eg.
$("."+project_tag).children(".project-header").click( (function(tag) { return function(event){ // returns function bound "tag" parameter value $("."+tag).children(".slideable").slidetoggle(400); } })(project_tag) // use current value of project_tag );
Comments
Post a Comment