声明一个变量以便稍后在代码中使用?

时间:2018-05-30 08:02:41

标签: javascript jquery

我试图理解如何声明一个我以后可以在我的jquery代码中使用的变量。下面我尝试使用var id,但是当我尝试在alert(id)中使用它时,它似乎被遗忘了。我怎样才能做到这一点?非常感谢。

$(document).ready(function() {

$('.credit_btn').on('click', function() {

   //Declare variables

    var id = ($(this).prop("value"));
    var test_id = $(this).parent().parent().attr("id");

    //Load modal
    $('.modal-container').load('modalbox.php?id=' + id, '&position_id=' + test_id,
      function() {
        $('#myModal').modal({
          show: true
        });
      }
    );
  });

  $(document).on("click", ".myBtn", function() {

    alert(id); //Var id is lost.

  });
}); //close doc

3 个答案:

答案 0 :(得分:5)

公开声明var id而不是$('.credit_btn').on('click', function() {内部,并且您已完成。

您当前的代码:

$(document).ready(function() {
    $('.credit_btn').on('click', function() {

       //Declare variables

        var id = ($(this).prop("value"));
        var test_id = $(this).parent().parent().attr("id");

        //Load modal
        $('.modal-container').load('modalbox.php?id=' + id, '&position_id=' + test_id,
          function() {
            $('#myModal').modal({
              show: true
            });
          }
        );
      });

      $(document).on("click", ".myBtn", function() {

        alert(id); //Var id is lost.

      });
    }); 

更改为:

$(document).ready(function() {
var id;
$('.credit_btn').on('click', function() {

   //Declare variables

    id = ($(this).prop("value"));
    var test_id = $(this).parent().parent().attr("id");

    //Load modal
    $('.modal-container').load('modalbox.php?id=' + id, '&position_id=' + test_id,
      function() {
        $('#myModal').modal({
          show: true
        });
      }
    );
  });

  $(document).on("click", ".myBtn", function() {

    alert(id); //Var id is lost.

  });
}); 

答案 1 :(得分:0)

与所有词法作用域一样,在块中声明id,以便它使用的任何地方都在同一个块或后代块中:

$(document).ready(function() {
  var id;
  $('.credit_btn').on('click', function() {
    id = ($(this).prop("value"));
    var test_id = $(this).parent().parent().attr("id");
    //Load modal
    $('.modal-container').load('modalbox.php?id=' + id, '&position_id=' + test_id, function() {
      $('#myModal').modal({
        show: true
      });
    });
  });

  $(document).on("click", ".myBtn", function() {
    alert(id);
  });
}); //close doc

答案 2 :(得分:0)

尝试在回调函数范围之外声明变量,然后在回调函数

中使用它
 $( function() {
 var id;
 $('.credit_btn').on('click', function() {
   id=1;
 })

 } );
相关问题