简体   繁体   English

jQuery:如何获取外部事件函数的变量

[英]Jquery: How to get variable outside event function

This my code. 这是我的代码。

   /**
     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);

I would like to put our variables ($h_height) out of the function. 我想将我们的变量($ h_height)放在函数之外。 I used console.log to display. 我用console.log来显示。 it show undefined 它显示未定义

To Make Global Variables in Jquery 在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();
    }
})

If you want to print value using Console.log Then remember we are setting its values after some event triggers . 如果要使用Console.log打印值,请记住,我们将在某些事件触发器之后设置其值。 So by default its value could be undefined as it is undefined by default and its value gets set after a particular event like click event in my case 因此,默认情况下它的值可能是未定义的,因为默认情况下它是未定义的,并且它的值在特定事件(例如我的情况下,例如click事件)之后设置

Jquery Fiddle To Show How To Trigger Value of Global Variable in Jquery Jquery Fiddle演示如何在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" /> 

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

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