是否可以访问另一个 if 语句中的对象?因为情况是这样的。
我有一个编辑按钮,它将设置 <div>
至contenteditable
。所以如果我按下取消按钮, <div>
内的文本也应该重置。现在我的 JavaScript 是这样的
$('.class').on('click','.etc',function(){
var orig = {};
$a = $(this).('.etc').text().trim(); // just getting the text of the button
if($a == "Edit") // just checking if edit button
{
orig.text = $(this).find('original-text').text(); // should store the original text
}
else if ($a == "Cancel")
{
// the div must be set to the original text
alert(orig.text); // undefined
}
});
我真的迷路了
最佳答案
在 if
和 else
条件均可访问的范围内声明变量,或者在全局范围内声明变量。但在尝试访问其属性之前,请确保它已初始化!
var orig = {text:""};
$('.class').on('click','.etc',function(){
if($a == "Edit") // just checking if edit button
{
orig.text = $(this).find('original-text').text();
}
else if ($a == "Cancel")
{
alert(orig.text);
}
});
关于javascript在另一个if语句中获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32701583/