Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从一个函数访问另一个函数的JavaScript变量_Javascript_Jquery_Function_Variables - Fatal编程技术网

如何从一个函数访问另一个函数的JavaScript变量

如何从一个函数访问另一个函数的JavaScript变量,javascript,jquery,function,variables,Javascript,Jquery,Function,Variables,如何从一个位置访问JavaScript变量单击事件函数到另一个位置 我有一个变量imdid,我想在我的不同点击事件中访问这个变量,我该怎么做 $( document ).ready(function() { $(".img-upload").click(function(){ //$("#modal").modal('show'); var imdid = $(this).attr("imgid"); }); $(".im

如何从一个位置访问JavaScript变量单击事件函数到另一个位置

我有一个变量
imdid
,我想在我的不同点击事件中访问这个变量,我该怎么做

$( document ).ready(function() {


    $(".img-upload").click(function(){

        //$("#modal").modal('show');

        var imdid = $(this).attr("imgid");



    });


    $(".img-gallary").click(function(){

        var imgsrc = $(this).attr("src");

        alert(imgsrc);

        alert(imdid);

    }); 


});

});

非常感谢您在全球宣布imdid。只需从imdid中删除var keywork,它将被全局声明。在javascript中,如果您声明一个没有var的变量,或者让关键字使其可用性变为全局

$(".img-upload").click(function() {

  //$("#modal").modal('show');

  imdid = $(this).attr("imgid");

});


$(".img-gallary").click(function() {

  var imgsrc = $(this).attr("src");

  alert(imgsrc);

  alert(imdid);

});

您可以指定窗口变量:

$( document ).ready(function() { 
    $(".first").click(function(){ 
        //variable test 
        window.test = 10;  
    }); 
    $(".second").click(function(){ 
    console.log(window.test); 
    });   
}); 
由于javascript中的属性,您必须声明变量
var imdid
外部。单击事件处理程序以能够在两个事件处理程序内部访问它。试试看,例如:

$( document ).ready(function() {

  // Variables declared here will be available in both .click-events
  var imdid;

  $(".img-upload").click(function() {

  }

  $(".img-gallary").click(function(){

  }); 
}

在事件处理程序外部定义变量
imdid
。i、 e.
var-imdid$(.img upload”)。单击(函数(){imdid=$(this.attr(“imgid”);})通过全局声明imdid。只需从imdid中删除var keywork,它就会被声明globally@Sam值得一试,希望对你有用