【问题标题】:How to use elements attribute value as selector with jQuery如何使用元素属性值作为 jQuery 的选择器
【发布时间】:2010-07-22 06:44:08
【问题描述】:

我正在尝试使用锚的标题元素来确定目标通过 ajax 加载到哪个块元素中,目前它看起来像这样:

$(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")).show("slow"); //animation
                $($(this).attr("title")).html(html); //show the html inside the target div
            }
        }); //close $.ajax(
    }); //close delegate(
}); //close $(

这样做的重点是,我可以在内容 div 中加载标题为 #content 的页面上单击的链接,并将标题设置为 #subcontent 的链接加载到子内容 div 中。这可能吗,如果是,我做错了什么?

更新 好的,显然 $(this) 变量在进入 $.ajax 调用时发生了变化,因此通过将 $(this).attr("title") 放入变量中,然后调用该变量代替选择器,它按预期工作。

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

    逻辑对我来说似乎足够合理。想到两个可能的问题:ajax 调用可能失败,或者标题标签可能没有返回您期望的字符串。出于这个原因,我建议在您的 $.ajax 函数中添加一个 ajax 错误处理程序和一些额外的 console.logs,以帮助您从 firebug 或 web 检查器中了解正在发生的事情。

    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);
    }
    

    【讨论】:

    • 它告诉我 title 属性是未定义的,但是当我添加一个 alert($(this).attr("title"));在 preventDefault 调用之后,它告诉我正确的标题值。 $(this) 是否在 $.ajax 调用中的某个地方发生了变化?更新:显然它确实如此,通过将 title 属性值放入变量并使用该变量作为选择器,它可以工作。
    • 感谢您的帮助,如果没有您的建议,我永远不会找到解决方案。
    猜你喜欢
    • 2010-12-17
    • 1970-01-01
    • 2013-07-09
    • 2017-10-04
    • 1970-01-01
    • 2014-01-10
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多