PDA

View Full Version : jquery functions


attasz
03-27-2010, 01:15 PM
I wrote a script what didn't work fine,so i deleted everything except the basics:
$(document).ready(function(){
var num = 8;
var text = "";
var r = 1;
for(var a = 1;a <=2;a++)
{
for(var i = 1;i <=num;i++)
{
text += "<div class = 'keret'><img src = 'docs/" + i + ".png' class = 'kep' alt = '" + r + "'></div>";
r++;
}
}
$("#pic_box").html(text);

$(".kep").click(function(){ //first function
$(this).removeClass().addClass("selected");

});
$(".selected").click(function(){ //second function
alert("sys");
});
});
Shortly,i fill up the pic_box with pictures,if i click on a picture i give it the class: "selected".
But if i click on a picture with the class "selected",nothing happens.
If i take the 2. function inside the 1. function,it works,the alert pops up.
I don't understand why the second func can't work outside the first,is there some inheritance,or what?:confused:

Fumigator
03-27-2010, 11:25 PM
This happens because jQuery doesn't realize the element has now been assigned the class "selected". Your selector doesn't see the element as having that class because you dynamically assigned it after all the selectors got processed upon page load.

It's an easy fix; instead of using the .click(function() {}) function, use the .live('click', function() {}) function.

http://api.jquery.com/live/

attasz
03-28-2010, 06:49 AM
Thx man,it's a really understandable explanation with a really simple and good solution.Have a nice day! :thumbsup:

Ralph Shnelvar
04-04-2010, 06:14 AM
I agree with attasz.

Sometimes the most helpful solutions are the shortest.

Having said that, could Fumigator point to some online documentation that fleshes out his answer? Specifically, is there a document somewhere that backs up Fumigator's answer?

Fumigator
04-04-2010, 05:32 PM
I agree with attasz.

Sometimes the most helpful solutions are the shortest.

Having said that, could Fumigator point to some online documentation that fleshes out his answer? Specifically, is there a document somewhere that backs up Fumigator's answer?

In my first post I linked to jQuery's online documentation where the purpose of live() is explained in detail.