简体   繁体   中英

declared variable doesn't seem global

I declared my variable first - then have my jquery :

var cimg = '';
jQuery(function($) {
    $(".trigger").click(function() {
  var cimg = event.target.id;
  clickedimage();
  loadPopup();
});
});

Then the script outside the jquery :

function clickedimage()
  {
    var xmargin  = $(cimg).width()/2;
    var ymargin = $(cimg).height()/2;
    $("#popupimage").css('margin-left',-xmargin+'px')
    $("#popupimage").css('margin-top',-ymargin+'px')
    var Clicked = cimg.src;
    $('#popupimage').attr('src',Clicked);
  }

It doesn't seem to want to take on the cimg value supplied from the .trigger clicked event

What am I doing wrong here?

In the click event you do var cimg = ...; . The var keyword tells it to create a new local variable instead of using the one from the outer scope.

Remove the var inside the handler.

var cimg = '';
jQuery(function($) {
    $(".trigger").click(function(event) {
        cimg = event.target.id;
        clickedimage();
        loadPopup();
    });
});

You redeclaring var cimg which causes it to be a local variable inside function scope. In addition, you're not providing event , which also causes an error (some browsers allow referring to window.event though).

jQuery(function($) {
    $(".trigger").click(function(event) {
        cimg = event.target.id;
        clickedimage();
        loadPopup();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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