我有这段代码:
$("#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.
});
任何人都可以帮我吗?提前谢谢。
答案 0 :(得分:2)
非常简单,使变量全局
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.
});
答案 1 :(得分:1)
您可以在调用任何函数之前存储原始的window
DOM内容:
var pos;
$("#open").click(function(){
pos = $(window).scrollTop();
});
$("#close").click(function(){
$(window).height(pos);
});
文档
答案 2 :(得分:1)
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
}
}
示例:
<script type="text/javascript">
$(function() {
var app = new MyApp();
app.wire(); //wire handlers
});
</script>
答案 3 :(得分:1)
我在匿名函数中使用变量local:
(function() {
var context = {};
$('#open').click(function() {
context.pos = $(window).scrollTop();
});
$('#close').click(function() {
// Do something with context.pos
});
})();
您的代码和说明并未明确说明,但上述内容保留了您的代码的假设:除非单击“打开”,否则无法单击该关闭,并且在单击“关闭”之前无法再次单击“关闭”。但这实际上取决于你的代码 - 如果这个假设不正确,我会采用不同的方法(如果这个假设不正确,那么点击这里可能会导致未定义)。
答案 4 :(得分:0)
更安全的方式。
$("#open").click(function() {
$("#close").attr("data-pop", $(window).scrollTop());
});
$("#close").click(function() {
var pos = $(this).attr("data-pop");
});