javascript - 使用 this.text() 和 jquery 检索文本

标签 javascript jquery html ajax

我正在尝试使用此方法获取点击链接中的文本

    $(".ajax-append").click(function(event) { 
     $.get("includes/fight.php?name=test", function(html) { 

     console.log($(this).text());
     console.log($(this));

        // append the "ajax'd" data to the table body 
        $("table tbody").append(html); 
        // let the plugin know that we made a update 
        $("table").trigger("update"); 
        // set sorting column and direction, this will sort on the first and third column 
        var sorting = [[2,1],[0,0]]; 
        // sort on the first column 
        $("table").trigger("sorton",[sorting]); 
    }); 
    return false; 
}); 

标记看起来像这样

<div class="friend" id="friend6" style="padding 5px; height: 54px; margin-bottom: 10px;">
<div style="float: left; width: 54px;">
       <img style="border:2px solid #E1E1E1;" src="6.jpg"/>
</div>
<div id="name6" style="float: left; padding-top: 20px; padding-left: 10px; font-size: 14px; width: 200px">
    <a href="#" class="ajax-append" id="6">name 6</a>
</div>
</div>
<div class="friend" id="friend7" style="padding 5px; height: 54px; margin-bottom: 10px;">
<div style="float: left; width: 54px;">
    <img style="border:2px solid #E1E1E1;" src="7.jpg"/>
</div>
<div id="name7" style="float: left; padding-top: 20px; padding-left: 10px; font-size: 14px; width: 200px">
    <a href="#" class="ajax-append" id="7">name 7</a>
</div>

如果我使用特定的 ID,我可以获取 anchor 标记内的文本,但我尝试使用 $(this) 来实现此目的,并且警报消息始终未定义。

谁能指出出了什么问题吗?或者想出更好的方法来做到这一点?

谢谢。

最佳答案

试试这个:

$(".ajax-append").click(function(event) { 
    var element=this;
     $.get("includes/fight.php?name=test", function(html) { 

     console.log($(element).text());
     console.log($(element));

        // append the "ajax'd" data to the table body 
        $("table tbody").append(html); 
        // let the plugin know that we made a update 
        $("table").trigger("update"); 
        // set sorting column and direction, this will sort on the first and third column 
        var sorting = [[2,1],[0,0]]; 
        // sort on the first column 
        $("table").trigger("sorton",[sorting]); 
    }); 
    return false; 
});

关于javascript - 使用 this.text() 和 jquery 检索文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1245298/

相关文章:

javascript - AngularJS 选择 ng-model 值不在范围内

javascript - 如何将图像存储和检索到 localStorage?

jquery - 将 Google 图表导出到 Excel

javascript - 如何让 'button' 在 MouseDown 上创建一个可移动的 DIV,并将 'MouseDown' 切换到新的 DIV?

javascript - 关闭所有其他DIV和隐藏DIV的定位

html - 设置 CSS 网格中第一行的高度

javascript - 跨平台base64字节数组编码

javascript - 用于匹配特定格式 IP 的正则表达式

javascript - Chart.js - 正确使用对象数组

javascript - 如果取消选择一个输入,如何取消选择 "all"选择器