tags:

views:

331

answers:

1

hi.. i dynamically load html elements.. and used livequery() plugin to handle click events.. but only the first element could be clicked.

here's my initial DOM:

 <div id="styleList">
            <h4 class="subPaneTitle blurred">List of themes</h4>
            <ul>
                <li class="listHeader"><span class="themeID">Theme ID</span><span class="themeName">Theme Name</span>
                         <span class="themeAction">Action</span>
                </li>
            </ul>
            <p class="createNewStyle clearfix"><a id="createNewStyle" class="btnStyle1 blurred ui-corner-all">Create new theme</a></p>
        </div>

here's my code to load dynamically the elements from xml:

    $.get("http://localhost/ShopNGo_Blitz_revised_w_YAML/site_styles_list.xml",loadAllThemes);


    function loadAllThemes(data){
    $(data).find("style").each(function(){
     var thisStyle = $(this);
     var styleID = thisStyle.attr('id');
     var styleName = thisStyle.attr('name');
     var styleStatus = "";
     if(thisStyle.attr('status') == "used"){
      styleStatus = '<span class="statusIndicator">Current theme</span>';
     }
     $("#styleList ul").append('<li><span class="themeID">'+ styleID + '</span><span class="themeName">' + styleName + '</span><span class="themeAction"><a id="themePreview">Preview</a></span><span class="themeAction"><a id="themeEdit">Edit</a></span><span class="themeAction"><a id="themeDelete">Delete</a></span><span class="themeAction"><a id="themeUse">Use</a></span>' + styleStatus + '</li>');

    });
}

here's my code for the 'Edit' click event:

    $("div#styleList").find("ul").find("li").find("a#themeEdit").livequery("click",function(){ //this gets only the first element.
 var themeName = $(this).parent().prev().prev(".themeName").text();
 $("#siteStyleContent").tabs("select","#styleEditTabs");
 $("div#styleEditTabs").children("#themeName").text(themeName);
});
+2  A: 

You are using IDs as Classes. Check out all these questions for why this is a bad thing:

Essentially, IDs should be UNIQUE. When you have a set of something (like, say, edit links) the proper way of grouping them is with a class. When you search for #themeEdit jQuery is going to assume there is only one and return the first one, because that's the way it ought to be. You need to give the links a class of themeEdit and search for them as .themeEdit.

Furthermore, jQuery 1.3 has the live functionality built in, so if you are using that, there really is no need to go to the plugin for something like this.

Paolo Bergantino
thanks.. i hadn't realized this.
bgreen1989
.live doesn't support all the events yet until 1.4
Artem Russakovskii
He is using livequery for click, which is supported...
Paolo Bergantino