Javascript get对象在另一个if语句中

javascript get object inside another if statement

本文关键字:if 语句 另一个 get 对象 Javascript      更新时间:2023-09-26

是否可以在另一个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
    }
});

我真的很困惑

ifelse条件都可以访问的范围内声明变量,或者在全局范围内声明变量。但是在你尝试访问它的属性之前,要确保它已经初始化了!

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); 
    }
});

问题在变量orig的范围内。JS有函数级词法作用域。

所以回答你的标题问题,是的,你可以访问在if中的一个在else中创建的变量,只要else肯定发生在if至少发生一次之后。但这并不是导致你出现问题的真正原因。

你的问题是你试图在onclick函数之外持久化这个变量。当该函数结束时,变量的生命周期也随之结束。简单的修复方法是在函数外部声明它并使用JS闭包。

var orig = {};
$('.class').on('click', function () {
    if ($(this).text() == "Store") {
        orig.text = $("#display").text();
    } else if ($(this).text() == "Cancel") {
        alert(orig.text);
    }
});

我不得不调整一下,因为我不知道你的完整HTML,但它可以工作。


为了避免全局变量的不良做法,您可以为整个内容创建一个封闭作用域,如下所示:

(function () {
    var orig = {};
    $('.class').on('click', function () {
        if ($(this).text() == "Store") {
            orig.text = $("#display").text();
        } else if ($(this).text() == "Cancel") {
            alert(orig.text);
        }
    });
})();

在实际操作中