olo*_*olo 15 javascript jquery
如何将函数a_href = $(this).attr('href');值传递给global a_href,makea_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
Run Code Online (Sandbox Code Playgroud)
Aru*_*hny 35
你的代码看起来很好,除了如果变量声明在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();
}
})
Run Code Online (Sandbox Code Playgroud)
要使变量成为全局变量,一种解决方案是在全局范围内声明变量
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();
}
})
Run Code Online (Sandbox Code Playgroud)
另一种方法是将变量设置为窗口对象的属性
window.a_href = $(this).attr('href')
Run Code Online (Sandbox Code Playgroud)
为什么控制台打印未定义
您正在获取输出,undefined因为即使声明了变量,您也没有使用值初始化它,只有在a单击元素之后才设置变量的值,直到该变量具有该值undefined.如果您没有声明变量,它将抛出一个ReferenceError