如何将函数 a_href = $(this).attr('href');
值传递给全局 a_href
,使 a_href="home"
var a_href;
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
console.log(a_href);
//Output is undefined
最佳答案
你的代码看起来不错,除了如果变量声明在 dom 读取处理程序中,那么它将不是全局变量......它将是一个闭包变量
jQuery(function(){
//here it is a closure variable
var a_href;
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
})
要使变量成为全局变量,一种解决方案是在全局范围内声明变量
var a_href;
jQuery(function(){
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
})
另一种是将变量设置为窗口对象的属性
window.a_href = $(this).attr('href')
为什么控制台打印未定义
您得到的输出为 undefined
因为即使声明了变量,您还没有用值初始化它,变量的值仅在 a
之后设置。单击元素直到那个时候变量将具有值 undefined
.如果您没有声明变量,它将抛出 ReferenceError。
关于javascript - jQuery 使全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18995647/