我有一张这样的 table
表
<table id="adminTable" style="display: inline-block">
<tbody>
@foreach (var person in @Model)
{
<tr>
<td style="padding: 10px;">
<div id="userName" style="display: inline-block">
<h4 name="person" id="goProfile" class="elements" style="cursor: pointer; display: inline-block">@person.DisplayName</h4>
</div>
<div id="userButton" style="display: inline-block;float: right" >
<a id="update" href="#" class="btn btn-info" style="margin-left: 6px;">Update User</a>
<a id="delete" href="#" class="btn btn-warning" style="margin-left: 6px;">Delete User</a>
</div>
</td>
</tr>
}
</tbody>
</table>
看起来像这样;
我需要对这些人进行更新或删除操作。我需要知道当我按下 updateUser|DeleteUser 按钮时,我必须到达 USERNAME 才能进行编辑或删除。
我的 JS 在这里,但它是错误的:(
JS
$('#adminTable')
.find('tr')
.click(function () {
debugger;
var userName = $(this).find('td').text();
var operation = parseInt($('tr').index()) + 1;
$.ajax({
url: "/Admin/deleteUser",
type: 'POST',
data: { "DisplayName": userName, "op": operation },
success: function (data) {
window.location.href = 'Profile/ProfileScreen/?name=' + data.displayName;
}
});
});
在这段代码中,我有一个操作变量。如果我能找出我在做什么,我可以与 ajax 建立连接,但我无法到达。
非常感谢。现在我可以 sleep 了...
最佳答案
开始之前,请确保没有将重复的 Id 值分配给多个元素。您当前的代码正在为循环内的元素设置相同的 id 值。这是无效的 html!
您可以将要传递的信息保留在这些按钮上的 html 5 数据属性中。
<a href="#" class="user-action btn btn-info"
data-url="@Url.Action("deleteUser","admin")"
data-username="@person.DisplayName"
data-op="update" >Update User</a>
<a href="#" class="user-action btn btn-warning"
data-url="@Url.Action("deleteUser","admin")"
data-username="@person.DisplayName"
data-op="delete">Delete User</a>
现在您所要做的就是读取此数据属性值并根据需要使用。
$(function(){
$(".user-action").click(function(e){
e.preventDefault();
var d= { DisplayName : $(this).data("username"),
Operation : $(this).data("op")
};
var yourUrl= $(this).data("url");
// now make the ajax call
$.ajax({
url: yourUrl,
type: 'POST',
data: d,
success: function (data) {
// do something with the response data.
}
});
});
});
关于javascript - 使用JS查找表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41529291/