如何通过其值查找 HTML 元素
how to find html element by its value
我想通过其值查找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);
});
});
});
相关文章:
- 如何设置html元素填充的动画
- 删除对HTML元素的拖动
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 如何使用JQuery在Javascript中转换字符串中的HTML元素
- 一个html元素的克隆次数太多
- 使用AngularJS Directive WHITOUT$scope创建一个动态html元素
- 为什么我在Internet Explorer上看不到html元素
- 重新排列HTML元素的顺序并更改内容
- 使用.on动态添加jquery/js不知道的html元素
- 如果类不是一个选项,如何在使用 jQuery 时控制(避免)嵌套 html 元素的样式
- 如何将html元素添加到tampermonkey中
- 访问html元素值javascript
- 如何在HTML元素上创建函数,而不是将元素作为参数传递
- 自定义HTML元素属性未显示-Web组件
- 让HTML元素充当停止滚动的锚点
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- 替换HTML元素中的字符
- 如何将html元素添加为生成的内容
- 如何使用JavaScript在没有html dom的情况下隐藏html元素
- 使用JS加载HTML元素