无法在JS函数之间传递变量

时间:2017-12-21 03:33:52

标签: javascript jquery ajax

我遇到的问题是需要将“the_id”变量传递给“deleteEntry()”函数。我能够成功传递一个没有引号的整数,但是我无法将任何变量传递给该函数。尝试用引号或不用引号传递变量时得到的错误是 - “未捕获的ReferenceError:the_id未在HTMLInputElement.onclick中定义”。关于问题在哪里的任何建议?提前谢谢。

        var the_id = $(this).parents('tr:first').find('td:nth(4)').text();
        the_id = parseInt(the_id);
        $("#indate").remove();
        newDate = document.createElement("input");
        newDate.setAttribute("type","text");
        newDate.setAttribute("id","indate");
        newDate.setAttribute("placeholder",dateText);
        newDate.setAttribute("onfocus","(this.type='date')");
        newDate.setAttribute("onblur","(this.type='text')");
        $("#changeDateType").append(newDate);
        $("#description").attr("placeholder",descriptionText);
        $("#inamount").attr("placeholder",amountText);
        if(bill == "1"){
          $("#billcheck").prop("checked",true);
        }
        else {
          $("#billcheck").prop("checked",false);
        }
        $("#submitBill").remove();
        $("#deleteBill").remove();
        $('#submitBillInfo').append('<input type="submit" id="submitBill" value="Submit" onclick="submitEntry()">');
        $('#submitBillInfo').append('<input type="submit" id="deleteBill" value="Delete" onclick="deleteEntry(the_id)">');
        $("#billForm").removeAttr("onsubmit");
      }
}

function deleteEntry(nums){
  alert(nums);
  var c = confirm("Do you want to delete this item?");
  if( c == true){
    $(function(){
      $.ajax({
        type: 'POST',
        url: '../Js/deleteData.php',
        data: { data: nums },
      });
     });

1 个答案:

答案 0 :(得分:2)

因为您在函数体内定义了'the_id'变量,所以无法从HTML DOM中访问它。因此,当您单击删除按钮时,它将返回错误。

我认为你可以解决这个问题,在追加输入字符串之后分配一个事件监听器来删除输入。

首先,删除您插入的删除按钮上的onclick声明。

$('#submitBillInfo').append('<input type="submit" id="deleteBill" value="Delete">');

然后添加一个事件监听器来删除按钮:

$('#deleteBill').click(function(){ deleteEntry(the_id); })
相关问题