我在代码
中的变量范围有问题var ButtonPressed; //global SCOPE
$(document).ready(function()
{
function messageAlert()
{
$('#buttons').append('<input type="button" id="btn" value="Clickme" />');
return false;
}
messageAlert();
$('#btn').on("click", function()
{
ButtonPressed = 1;
});
}); //end document
//// UNDEFINED NOT WORKING
if (ButtonPressed === 1)
{
alert(ButtonPressed);
}
我尝试了有关范围教程的所有内容,但我无法显示变量ButtonPressed=1
GLOBAL。
有任何帮助吗?
答案 0 :(得分:2)
您将点击事件绑定到按钮var input: CGRect? {
set(value) {
guard let value = value else { return }
// process the value here
}
get {
return nil
}
}
以设置全局变量#btn
,除非您单击按钮,否则不会触发该变量。
当您的代码执行并到达块(在全局范围内)时,知道该按钮尚未被单击
ButtonPressed
变量if (ButtonPressed === 1)
{
alert(ButtonPressed);
}
将不会被设置,因为您没有点击该按钮,因此它不会提醒任何消息。
换句话说,if语句在单击处理程序
之前运行答案 1 :(得分:0)
解释你的代码。执行就是这样的(1) - &gt; (2) - &gt; (3)
var ButtonPressed; // executed as soon as the script tag is hit -- ( 1 )
$(document).ready(function()
{
//...... //executed ONLY AFTER the DOM is ready - (3 )
});
if (ButtonPressed === 1) //executed as soon as the script tag is hit - ( 2 )
{
alert(ButtonPressed);
}
如注释所示,首先执行var ButtonPressed
,然后执行跳转到if
检查。只有在DOM完全就绪后,$(document).ready
内的代码块才会执行。
这意味着所有全局范围代码的内容将首先执行,然后在文档内部执行
1)如果您的目的是点击按钮时显示提醒,请执行此操作
$('#btn').on("click", function()
{
ButtonPressed = 1;
alert(ButtonPressed);
// do all the stuff that should happen when a button is clicked
});
2)如果您打算检查按钮是否被点击?那么您可以使用setInterval
。使用此功能,您可以检查是否每按一次按钮点击一次按钮。如下所示。
var checkButtonStatus = setInterval(function(){
if (ButtonPressed === 1)
{
alert(ButtonPressed);
//do all your stuff as the button was clicked
clearInterval(checkButtonStatus ); // remove interval as you don't need to check again.
}
}, 1000);
注意: I would say option 2 is not efficient way of doing it, Go for option 1