Javascript jQuery全局var为';行不通
我想声明全局变量,但它一直在说Javascript jQuery全局var为';行不通,javascript,jquery,Javascript,Jquery,我想声明全局变量,但它一直在说undefined <div class="last">Blah</div> 我也试过了 $(document).ready(function() { var testing; $(document).on('click', '.last', function() { testing = $(this).html(); }) console.log(testing); }) 试试这个: $
undefined
<div class="last">Blah</div>
我也试过了
$(document).ready(function() {
var testing;
$(document).on('click', '.last', function() {
testing = $(this).html();
})
console.log(testing);
})
试试这个:
$(函数(){
var检验;
$('.last')。单击(函数(){
testing=$(this.html();
警报(测试);
});
});代码>
废话(单击此处)
您的代码运行良好,但不是您所期望的。在加载DOM时读取testing
变量,但在单击按钮后才给它一个值。相反,您需要一种读取窗口的方法。在设置变量后测试该变量。下面是一个使用按钮单击的示例
$(文档).ready(函数(){
$(文档).on('click','last',函数(){
window.testing=$(this.html();
})
$(“按钮”)。单击(函数(){
控制台日志(窗口测试);
});
})
设置
阅读
试试这个
var testing = "";
$(document).ready(function() {
$(document).on('click', '.last', function() {
testing = $(this).html();
});
console.log(testing);
});
编辑
尝试将简单值传递给变量,然后传递.last类值
var testing = "";
$(document).ready(function() {
$(document).click(function() {
testing = 1;
alert(testing);
});
});
您的代码运行良好,但不是您所期望的。在加载DOM时读取testing
变量,但在单击按钮后才给它一个值。还要注意,使用全局变量不是一件好事。如果您需要允许变量在不同的位置使用,请在document ready函数之前使用namespace.setvar testing
,它将作为全局变量运行。如果您在函数内部使用测试变量。我希望它能在函数之外使用&当用户单击它时,我还需要元素“last”的值。嘿,谢谢你的解释,你的代码正在工作。但我仍然感到困惑,为什么我必须使用点击按钮功能来获取值?为什么我不能使用console.log直接获取值,因为页面加载后,原始console.log会立即运行。此时未设置该值。然后单击按钮,比如页面加载5秒后,不再有代码读取变量的值。因此,我添加了一个新按钮,您可以随时单击该按钮来读取该值。