【问题标题】:How to access JavaScript variable from one function to another如何从一个函数访问 JavaScript 变量到另一个函数
【发布时间】:2023-03-23 12:55:02
【问题描述】:

如何从一个位置单击事件函数访问 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外部事件处理程序。即var imdid; $(".img-upload").click(function(){ imdid = $(this).attr("imgid"); });
  • 通过全局声明 imdid。只需从 imdid 中删除 var keywork 它将被全局声明

标签: javascript jquery function variables


【解决方案1】:

通过全局声明 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);

});

【讨论】:

  • @Sam Withworth 试试这个,希望这对你有用
【解决方案2】:

由于scopes 在javascript 中的性质,您必须在.click 事件处理程序的外部 声明变量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(){

  }); 
}

【讨论】:

    【解决方案3】:

    您可以分配窗口变量:

    $( document ).ready(function() { 
        $(".first").click(function(){ 
            //variable test 
            window.test = 10;  
        }); 
        $(".second").click(function(){ 
        console.log(window.test); 
        });   
    }); 
    

    【讨论】:

      猜你喜欢
      • 2022-10-24
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多