javascript – jquery绑定事件的问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – jquery绑定事件的问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1704字,纯文字阅读大概需要3分钟。
内容图文
![javascript – jquery绑定事件的问题](/upload/InfoBanner/zyjiaocheng/752/8069838130eb41b399f95c83d5981f87.jpg)
我是前端编程的新手.当我学习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>
运行此代码时,两个警报都会打印“hello”.我点击的第一个按钮除了“hi”警告.有人能解释我为什么会这样吗?这是礼仪行为吗?是因为范围限制吗?请帮帮我.
解决方法:
这里有很多大致正确的解释,但令我惊讶的是,没有人抛出关键概念:封闭.
基本上发生的事情是当你声明你的两个函数时,它们声明的范围形成一个闭包.这意味着该闭包内的变量仍然可用于函数.换一种说法:
$(document).ready(function(){
// this begins a closure
var msg ="hi";
// you are simply declaring a function here, not calling it
$("#test1").click(function(){alert(msg)});
msg ="hello";
// ditto
$("#test2").click(function(){alert(msg)});
// the end of the closure...msg has the value "hello"
});
然后一段时间过去了,点击事件就会被调用.附加到click事件的函数仍然可以访问闭包(在其中msg的值为“hello”).
在闭包内“捕获”变量值的传统方法是创建一个“Immediately Invoked Function Expression” (IIFE).基本上你可以把它想象成创建一个包含变量的直接值的全新闭包.您可以重新编写代码以使用这样的IIFE:
$(document).ready(function(){
// this begins a closure
var msg ="hi";
// the following creates an anonymous function with a single parameter
// AND invokes it immediately, creating another closure in which the
// value of msg1 is "hi".
(function(msg1){
$("#test1").click(function(){alert(msg1)});
})(msg);
msg ="hello";
// ditto
(function(msg2){
$("#test2").click(function(){alert(msg2)});
})(msg);
});
我希望这会使发生的事情变得更加清晰,以及如何获得您正在寻找的东西.
内容总结
以上是互联网集市为您收集整理的javascript – jquery绑定事件的问题全部内容,希望文章能够帮你解决javascript – jquery绑定事件的问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。