我从MVC控制器获取了具有值的JSON数据
[{"OperationName":"All","PrivilegeName":"Roles Crud"},{"OperationName":"Read","PrivilegeName":"Roles Read Delete"},{"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},{"OperationName":"Read","PrivilegeName":"Roles Update"},{"OperationName":"Update","PrivilegeName":"Roles Update"}]
我已使用AJAX将此JSON数据显示到HTML表中。
$(document).ready(function () {
//debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "source={}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr id='trName_" + index + "'>";
row += "<td id='td_OpName" + index + "'>" + item.OperationName + "</td>";
row += "<td id='td_PrivName" + index + "'>" + item.PrivilegeName + "</td>";
row += "<tr>";
});
$("#table1").html(row);
console.log(data);
var source = [];
source.push(data);
console.log(source);
},
error: function (result) {
alert("Error");
}
})
});
当我单击特定行时,我正在尝试从表中选择单个行,它应在警报框中显示其值 但是,它显示的是整个表的JSON数据onClick。 我应该对此JQuery函数进行什么更正?
$(document).ready(function () {
$("#table1 tr").click(function () {
debugger;
$('.selected').removeClass('selected');
$(this).parents('tr').addClass('selected');
})
});
答案 0 :(得分:1)
据我所知,您想显示选定的行数据,对于这种情况,您可以尝试这样
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
var _index = $(this).attr("id").replace("trName_", "");
var _currentSelectedRow = source[_index];
console.log(_currentSelectedRow);
});
在ajax成功块中,您将变量声明为
var source = [];
source.push(data);
相反,将'source'变量声明为全局变量,然后将Ajax成功块中的json数据分配给'source'。
source = data;
答案 1 :(得分:0)
如果我正确理解了您的问题,那么解决方法是:
$(document).ready(function () {
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected'); // remove .parents('tr')
})
});
通过进行上述更改,这将仅导致用户在#table1
中单击的行(即与$(this)
对应的行元素)被应用selected
类。 / p>
确保单击处理程序内的$(this)
与表行元素相对应,请注意,单击处理程序已通过tr
选择器绑定到#table tr
元素。希望这会有所帮助!