Jquery:如何在事件函数之外获取变量

Jquery: How to get variable outside event function

本文关键字:获取 变量 函数 事件 Jquery      更新时间:2023-09-26

这是我的代码。

   /**
     Sticky Header
    **/
    var $h_height;
    $(".site-header").sticky({
        topSpacing:0,
    });
    $('.site-header').on('sticky-start', function() {
        $h_height = $(this).outerHeight();
    });
    $('.site-header').on('sticky-end', function() { $(this).parent().css('height', 'auto'); });
    console.log($h_height);

我想把我们的变量($h_height)从函数中剔除。我使用控制台.log来显示。它显示未定义

在 Jquery 中创建全局变量

var a_href;
jQuery(function(){
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');
          console.log(a_href);  
         //output is href value of clicked link
        e.preventDefault();
    }
})

如果要使用控制台打印值.log请记住,我们正在 在某些事件触发器之后设置其值 .因此,默认情况下,它的值可能是未定义的,因为它默认情况下是未定义的,并且其值是在特定事件(例如我的情况下的单击事件)之后设置的

Jquery 小提琴展示如何在 jquery 中触发全局变量的值

//Global Variable 
var a_href;
//Global Variable Value Triggered After Button1 Click
 $('#bt').on('click', function(e){
        a_href = $("#tx").val();
   alert(a_href);
          //console.log(a_href);  
         //output is href value of clicked link
        e.preventDefault();
    });
    
    //Global Variable Value Triggered After Button2 Click
     $('#bt1').on('click', function(e){
        a_href = $("#tx1").val();
       alert(a_href);
          //console.log(a_href);  
         //output is href value of clicked link
        e.preventDefault();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="hh" id="tx" />
<input type="button" value="Button1" id="bt" />
<br/>
<br/>
<input type="text" value="hh1" id="tx1" />
<input type="button" value="Button2" id="bt1" />