jquery绑定事件的问题

Lol*_*lly 3 javascript jquery jquery-ui

我是前端编程的新手.当我学习Jquery时,我遇到了这个问题.这是我的下面的代码

<script type="text/javascript">
$(document).ready(function(){
  var msg ="hi";
  $("#test1").click(function(){alert(msg)});
  msg ="hello";
  $("#test2").click(function(){alert(msg)});
});
</script>
</head>
<body>

<button id="test1">test1</button>
<button id="test2">test2</button>
Run Code Online (Sandbox Code Playgroud)

运行此代码时,两个警报都会打印"hello".我点击的第一个按钮除了"hi"警告.有人能解释我为什么会这样吗?这是礼仪行为吗?是因为范围限制吗?请帮帮我.

Nea*_*eal 5

你有一个范围问题.

当你到达实际点击的代码时 msg === "hello"