gpt4 book ai didi

javascript - 如何通过值查找html元素

转载 作者:行者123 更新时间:2023-11-28 16:16:40 25 4
gpt4 key购买 nike

我想通过它的值找到一个 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);
});
}

这段代码很好,但它仅将“已保存”响应附加到第一个用户名,因为到循环结束时,所有用户名都有id='followed'

这就是为什么,我想通过它的值找到 html 元素。例如“用户名”。
是否可以?

最佳答案

您可以使用context参数来更改传递给 AJAX 请求的成功回调的上下文。

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

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

好吧,现在我们已经清理了标记,让我们低调地订阅 .click()本次事件<li> :

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

关于javascript - 如何通过值查找html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11280091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com