简体   繁体   English

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

[英]Passing variable from one Jquery function to another

What im trying to do here is getting the id of a table on click function and then when i click the delete button it would get that id and delete it. 我在这里试图做的是获取单击功能表的ID,然后当我单击Delete按钮时,它将获得该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) {
               }
});
});

what am i doing wrong here 我在这里做错了什么

Your variable id is only valid inside that function. 您的变量ID仅在该函数内有效。 Try either - using the variable in a scope accessible for both functions - use the html-data attributes in the tr tag 尝试其中一种-在两个功能都可以访问的范围内使用变量-在tr标记中使用html-data属性

 $("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);
    }
});
 });

it got fixed by using sessionstorage thanks everyone 它通过使用sessionstorage修复了,谢谢大家

I assume you have a button on each row in the following, and it is a row you want to delete. 我假设您在下面的每一行上都有一个按钮,并且这是您要删除的行。 To grab the ID of the row I. 抢行的ID。

Each row of the table have a unique ID. 表格的每一行都有唯一的ID。 The Jquery function below use the "closest" method and grabs the ID. 下面的Jquery函数使用“最近”方法并获取ID。 From there you can delete it. 从那里您可以删除它。

Here is the code, not tested, but it should work :-) 这是代码,未经测试,但应该可以工作:-)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM