javascript - 如何找到动态表的第二行并在jquery中更改其值?
问题描述
我有一些动态表数据,这些数据是根据我在后端拥有的用户数量创建的。这只是一个简单的获取状态。但是,我在使用该动态 html 上的切换按钮时遇到了问题。我的切换按钮动机是:如果用户打开它,它会将状态更改为“ACTVIE”,如果关闭,则会显示“Inactive”。这工作正常,并且在切换时也会在数据库中更新更改。但是除非我刷新页面,否则状态不会在那一刻改变。
现在,我很困惑如何调用该表的确切行。
到目前为止我所做的我调用了 的所有行数据second row
,并且更改反映在 all 表上。但我只想更改我选择的切换表数据。
$('#dynamicUserDiv').on("change", "input.userStatus", function () {
var userId = $(this).closest("div.userDiv").attr("userId");
var isChecked = $(this).is(":checked");
$.ajax({
type: "GET",
url: "/status",
data: {
userId: userId,
isActive: isChecked
},
success: function (response) {
console.log(response) // this response return Active or Inactive based on toggle switch
$('.myTable tr:nth-child(2)').html(response);
},
async: true
});
}
这$('.myTable tr:nth-child(2)')正在返回所有表的所有第二行,这就是为什么我的 chagnes 反映在所有动态表的所有第二行上,但我只想选择那个表在哪个切换被点击
主要动态行:
$.each(user, function (index, item) {
var $itemUser = '<div class="col-md-6 userDiv" userid="' + item.id + '">'
+ '<div class="dash-widget dash-widget5">'
+ '<div class="dash-widget-info">'
+ '<div class="innerTableHeaderFile"><label class="">' + item.userName + '</label></div>'
+ '<table class="myTable">'
+ '<tbody>'
+ '<tr>'
+ '<td>User Name:</td>'
+ '<td>' + item.userName + '</td>'
+ '</tr>'
+ '<tr>'
+ '<td>User Status:</td>'
+ '<td>' + item.status + '</td>' // this is where I want to show the changes when toggle is on/off
+ '</tr>'
+ '<td>User Toggle:</td>'
+ '<td>'
+ '<label class="switch">'
+ '<input class = "userStatus" type="checkbox" ';
$itemUser += item.status == "ACTIVE" ? 'checked >': '> ';
$itemUser += '<span class="slider round"></span>'
+ '</label>'
+ '</tr>'
+ '</tbody>'
+ '</table>'
+ '</div>'
+ '</div>'
+ '</div>'
});
我怎样才能做到这一点?任何的想法?谢谢
解决方案
存储对 userDiv 实例的引用,以便在成功回调运行时查找其中的表行
$('#dynamicUserDiv').on("change", "input.userStatus", function () {
// store reference to parent that can be used in success callback
var $userDiv = $(this).closest("div.userDiv");
var userId = $userDiv.attr("userId");
var isChecked = $(this).is(":checked");
$.ajax({
// ...
success: function (response) {
// find the table within current userDiv
$userDiv.find('.myTable tr:nth-child(2)').html(response);
},
async: true// redundant since this is default
});
})
推荐阅读
- javascript - 对齐注释器 (Javascript/HTML) - 如何解决与具有相同前缀的变量的混淆
- regex - 以数字开头但以数字结尾的字符串的正则表达式到熊猫数据帧的子集
- c - 通过 libusb_interrupt_transfer 返回的数据值不一致
- swift - 来自 ViewController 的 UINavigation 控制器
- javascript - 而循环故障与div值
- c++ - Brainfuck 解释器在循环方面存在特殊问题
- r - 如何使用 R 的密码库手动输入密钥
- sql - Excel-VBA-Query 有没有办法通过 Refresh.All 来提高 Excel VBA 的速度?
- python - 使用python打开程序(不和谐)
- jquery - 如何使用 Vuejs 替换这个 jquery 代码?