문제

So I am creating a TagCloud for my site and am having issues being able to use JQuery to alert me of the selected link. The site created the links just fine, gives them the class of 'tagLink', but when I try to alert the number of elements with that class, it gives me 0. Any ideas?? Here is my code:

    $(function() {  
    //get tag feed  
    $.getJSON("tagcloud/tagcloud.php?callback=?", function(data) {  
          //create list for tag links  
        $("<ul>").attr("id", "tagList").appendTo("#tagCloud");  
        //create tags  
        $.each(data.tags, function(i, val) { 
            //create item  
            var li = $("<li>");  
            //create link  
            $("<a>").addClass('tagLink').text(val.tag).attr({title:"See all pages tagged with " + val.tag, href:"tags/" + val.tag + ".php", id: val.tag}).appendTo(li);  
            //set tag size  
            li.children().css("fontSize", (val.freq / 10 < 1) ? val.freq / 10 + 1 + "em": (val.freq / 10 > 2) ? "2em" : val.freq / 10 + "em");
            //add to list  
            li.appendTo("#tagList");  
        });   
    }); 

     //Increase database if link is clicked 
    alert($('.tagLink').size());//Test how many exist
    $('.tagLink').click(function(){
        var id = $(this).attr('id');
        $.ajax({    
            url: "tagcloud/tagcloud.php",
            type: "POST",
            data: {clicked : id}
        });
    });


});
도움이 되었습니까?

해결책

getJSON is asynchronous so your selector gets run before the tag links get added. Move the taglink click handler assignment inside your AJAX callback.

다른 팁

You can use $.get() or $.ajax() instead.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top