开发者

How to use elements attribute value as selector with jQuery

I am trying to use the title element of an anchor to determine which block element the target gets loaded into via ajax, currently it looks like this:

$(document).ready(function() {
    $('#content').load('overview.php'); //by default initally load text from overview.php
    $('body').delegate('a.ajax', 'click', function(e) { //start function when any link is clicked
        e.preventDefault();
        var content_show = $(this).attr("href"); //retrieve href of link so we can load the correct file
        $.ajax( {
            method: "get", url: content_show,data: 0,
            beforeSend: function(){$("#loading").show("fast");}, //show loading just when link is clicked
            complete: function(){ $("#loading").hide("fast");}, //stop showing loading when the process is complete
            success: function(html) { //so, if data is retrieved, store it in html
                $($(this).attr("title")).sh开发者_Go百科ow("slow"); //animation
                $($(this).attr("title")).html(html); //show the html inside the target div
            }
        }); //close $.ajax(
    }); //close delegate(
}); //close $(

The entire point of this is so I can have links that are clicked on from one page with the title #content load in the content div, and the links with the title set to #subcontent load in the subcontent div. Is this possible, and if so, what am I doing wrong?

Update ok, so apparently there is a change in the $(this) variable as it enters the $.ajax call, so by putting the $(this).attr("title") into a variable and then calling the variable in place of the selector, it works as intended.


The logic appears sound enough to me. Two possible issues come to mind: The ajax call might be failing, or the title tag might not be returning the string you expect it to. For this reason I would suggest adding an ajax error handler and some additional console.logs to your $.ajax function help you get an idea what is going on from firebug or web inspector.

success: function(html) {
    console.log("The title tag is: " + $(this).attr("title"));
    $($(this).attr("title")).show("slow");
    $($(this).attr("title")).html(html);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
    console.log("An ajax error occurred: "+errorThrown);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜