views:

105

answers:

2

What I'm trying to achieve, is to output a json list that contains a list of Css classes, and their corresponding url records, i.e.

var jsonList = [{"CSSClass":"testclass1","VideoUrl":"/Movies/movie.flv"},{"CSSClass":"testclass2","VideoUrl":"/Movies/movie2.flx"}]; //]]>

foreach item in the list I am adding a click event to the class...

$.each(script, function() {
        $("." + this.CSSClass, "#pageContainer").live('click', function(e) {
            videoPlayer.playMovie(this);
            return false;
        });
    });

What I'm wondering, is if I can somehow get the corresponding url from the jsonlist, without having to loop through them all again, searching for CSSClass, or adding the url to the link as an attribute?

+1  A: 

Absolutely, you just need to capture the your object so that the click function's closure has access to the right thing when it fires. Something like this should work:

$.each(script, function() {
    var vid = this;
    $("." + vid.CSSClass, "#pageContainer").live('click', function(e) {
        videoPlayer.playMovie(vid.VideoUrl);
        return false;
    });
});
Alconja
Was just about to answer the same. +1
Jacob Relkin
+2  A: 

you can add an Index and an Item parameter to the callback function in $.each method.

$.each(script, function(i, item) { 
   $("." + item.CSSClass, "#pageConainer").live("click", function() {
       videoPlayer.playMovie(item.VideoUrl);
       return false;
   });
});
  • "i" will be a counter of each iteration within the json object
  • "item" will represent the object in use
GerManson