简体   繁体   English

jQuery中的变量范围

[英]variable scope in jquery

I'm trying to access the value of a variable that is set inside a .click function outside of the function but I'll get the error, can anyone please tell me what I'm doing wrong? 我正在尝试访问在函数之外的.click函数中设置的变量的值,但会收到错误消息,有人可以告诉我我在做什么错吗?

var id;
var currentPosition;
var slideWidth = 368;
var slides;
var numberOfSlides;

$('#accordion_catering h3').click(function() {
    id = $(this).attr('id');
    $('#' +id+'_gallery').show();
    //alert(id);//works
});
alert(id); // is undefined

// Because id is undefined these don't work .

slides = $('.' + id + '_slide');
numberOfSlides = slides.length;

仅在click事件处理程序至少运行一次时才设置id,因为您是在事件处理程序中设置id变量

click did not occure yet, so id is not set ... it's not about variable-scopes, more about events and their handlers :) 点击还没有发生,所以没有设置id ...这与可变范围无关,与事件及其处理程序有关:)

as you added a cmt, i adapted my solution as following: 当您添加cmt时,我对我的解决方案进行了如下修改:

var currentPosition;
var slideWidth = 368;
var slides;
var numberOfSlides;
$(document).ready(function() {
    var element = $('#accordion_catering h3');
    element.click(function() {
        var id = $(this).attr('id');
        DisplayGallery(id);
    });
    element.trigger('click'); // maybe you want to trigger it
});
function DisplayGallery(id) {
    $('#' + id +'_gallery').show();
    slides = $('.' + id + '_slide');
    numberOfSlides = slides.length;
}
var id;  
var currentPosition;  
var slideWidth = 368;  
var slides;  
var numberOfSlides;  
$(document).ready(function() {  
   $('#accordion_catering h3').click(function() { 
        id = $(this).attr('id'); 
        $('#' +id+'_gallery').show(); 
        //alert(id);//works 
        slides = $('.' + id + '_slide'); 
        numberOfSlides = slides.length; 
    }); 
    $('#accordion_catering h3').trigger('click');
    alert(id); // is defined 
)};

So, basically, do not access id until this event has fired, it will then be set. 因此,基本上,在触发此事件之前,请勿访问id,然后将其设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM