将变量从一个Jquery函数传递给另一个

时间:2017-08-22 05:43:16

标签: jquery ajax

我在这里尝试做的是获取点击功能的表格的id,然后当我点击删除按钮时,它将获得该ID并删除它。

$("table tr").click(function () {
var id;
  $(this).removeClass('table-hover');
$(this).css("background-color", "#4682B4");
id = $(this).find(".id").html();
alert("Are you sure you want to delete data with id = " + id);  //using just to check if its getting the id of the row


});


 $('.btnDelete').click(function () {


$.ajax({
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    url: 'EmployeeDelete',
    data: JSON.stringify({ id: id }),
    success: function (data) {
               }
});
});

我在这里做错了什么

3 个答案:

答案 0 :(得分:1)

您的变量ID仅在该函数内有效。试试   - 在两个函数都可访问的范围内使用变量   - 使用tr标签中的html-data属性

答案 1 :(得分:1)

 $("table tbody tr").click(function (event) {


$(this).removeClass('table-hover');
$(this).css("background-color","#4682B4");
if (typeof(Storage) !== "undefined")
{
    sessionStorage.empID = $('td.id', this).html();
}
else{
    document.getElementById("result").innerHTML = "Sory, browser does not support  web storage";
    }

$.ajax({
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    url: 'getID',
    data: JSON.stringify({ empID: sessionStorage.empID }),
    success: function (data) {
    },
    failure: function (response)
    {
        $('#result').html(response);
    }
});
 });

通过使用sessionstorage感谢每个人

来解决它

答案 2 :(得分:0)

我假设您在下面的每一行都有一个按钮,它是您要删除的行。要获取行I的ID。

表格的每一行都有一个唯一的ID。下面的Jquery函数使用“最近”方法并获取ID。从那里你可以删除它。

以下是未经测试的代码,但应该可以使用: - )

var button = $('.MyButtonClass');    $(button).on( 'click', function () {
        var rowID = $(this).closest("tr").attr("id");
        //Delete the row });
相关问题