如何通过其值查找 HTML 元素

how to find html element by its value

本文关键字:HTML 元素 查找 何通过      更新时间:2023-09-26

我想通过其值查找html元素。我尝试使用id,但我的情况很脆弱:

伪代码:

for user in users:
 <li id="followed" onclick="follow($(this).text())"><a class="follow">user.name</a></li>
endfor

我希望每个用户名都是可点击的,我将他保存到数据库中并将"保存"附加到用户名的末尾。 像这样:

"username" ==> after click: "username saved"

我是通过ajax来做的。

function follow(data){
    var Him = data;
    alert(Him);
    $.ajax({
        url: "/follow",
        type: "POST",
        datatype: "html",
        data: {Him: Him}
    }).success(function(response){
        $('#followed').append(response);
    });
}

这段代码很好,但它只将"saved"响应附加到第一个用户名,因为在循环结束时,所有用户名都id='followed' .

这就是为什么,我想通过其值找到html元素,例如"用户名"。
可能吗?

可以使用

context 参数更改传递给 AJAX 请求的成功回调的上下文。

但首先让我们从清理标记开始,如果这是一个循环,请使用类名而不是 id,因为如您所知,id 在 HTML 中必须是唯一的:

for user in users:
    <li class="followed"><a class="follow">user.name</a></li>
endfor

好了,现在我们已经清理了标记,让我们不显眼地订阅此<li>.click()事件:

$(function() {
    $('.followed').click(function() {
        // Remark: maybe you wanna get just the username inside the anchor in which case
        // you probably need "var Him = $('a', this).text();"
        var him = $(this).text();
        $.ajax({
            url: '/follow',
            type: 'POST',
            dataType: 'html',
            context: this,    // <!-- Here, that's the important bit
            data: { him: him },
        }).success(function(response) {
            // since we have used the context, here 'this' will no
            // longer refer to the XHR object (which is the default) but
            // to whatever we have passed as context (in our case this
            // happens to be the <li> that was clicked) => we can be certain
            // that we are updating the proper DOM element
            $(this).append(response);
        });
    });
});