[英]Store variable from one event handler to be used by another event handler
I have this code: 我有以下代码:
$("#open").click(function()
{
var pos = $(window).scrollTop();
/* the next lines of code affects the value
* of 'pos'.
*/
});
$("#close").click(function()
{
var pos = /* what i want here is the $(window).scrollTop();
before the #open event handler changes it's value. */
//another code of mine.
});
Can anyone help me with this? 谁能帮我这个? Thanks in advance.
提前致谢。
it's very simple, make variable global 非常简单,将变量设为全局
var pos; //global variable
$("#open").click(function()
{
pos = $(window).scrollTop();
/* the next lines of code affects the value
* of 'pos'.
*/
});
$("#close").click(function()
{
// use pos here accordingly
//another code of mine.
});
You can store the original window
DOM contents before you call any functions: 您可以在调用任何函数之前存储原始
window
DOM内容:
var pos;
$("#open").click(function(){
pos = $(window).scrollTop();
});
$("#close").click(function(){
$(window).height(pos);
});
Docs
文件
You could just organize a little your code and do this:
function MyApp(){
var self = this;
this.pos = "";
this.temp = $(window).scrollTop(); //store initial value
this.wire = function(){
$("#open").click(self.open);
$("#close").click(self.close);
}
this.open = function(){
self.pos = $(window).scrollTop();
/* the next lines of code affects the value
* of 'pos'.
*/
}
this.close = function(){
self.pos = /* what i want here is the $(window).scrollTop(); before
* the #open event handler changes it's value.
*/
//another code of mine.
var original = self.temp; //here get the initial stored value
}
}
Example: 例:
<script type="text/javascript">
$(function() {
var app = new MyApp();
app.wire(); //wire handlers
});
</script>
I'd use a variable local to an anonymous function: 我将使用匿名函数本地的变量:
(function() {
var context = {};
$('#open').click(function() {
context.pos = $(window).scrollTop();
});
$('#close').click(function() {
// Do something with context.pos
});
})();
Your code and explanation don't make this clear, but the above maintains an assumption from your code: That close cannot be clicked unless open has been clicked, and open cannot be clicked again until close has been clicked. 您的代码和解释不清楚,但是上面的代码保留了一个假设:除非单击了打开,否则无法单击关闭,除非单击了关闭,否则无法再次单击打开。 But that really depends on your code - if that assumption isn't true I'd approach it differently (if that assumption isn't true, clicking close here risks getting an undefined).
但这实际上取决于您的代码-如果该假设不成立,我将采取不同的处理方式(如果该假设不成立,则在此处单击关闭可能会导致不确定)。
More safe way. 更安全的方法。
$("#open").click(function() {
$("#close").attr("data-pop", $(window).scrollTop());
});
$("#close").click(function() {
var pos = $(this).attr("data-pop");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.