如何检查使用 jQuery 单击后退按钮后是否出现页面?

How to check if a page comes after clicking the back button using jQuery?

我有一个表格,我使用 jQuery 计算总金额。 我为此创建的函数是 updateTotal();

表单操作是另一个页面,操作页面有这个按钮:

<button class="btn btn-success" onclick="history.go(-1);" type="submit" name="edit">EDIT</button>

因此,当用户单击“编辑”按钮页面时,再次返回到表单(第一页)并且所有填写的详细信息都在那里,除了使用 jQuery 创建的重复字段。 示例表格在 js fiddle

我只想 运行 这个函数 updateTotal(); 如果用户通过单击“编辑”(基本上是浏览返回)按钮进入表单..

在 jQuery 中有什么方法可以做到这一点吗?

供将来参考的更新 - 我是这样解决的

html:

<input type="text" id="amount" name="amount[]" placeholder="Amount" required="required" class="form-control inputChangeVal reqF reqFamount" data-js-input-type="number" />

和 jQuery :

jQuery(document).ready(function() {
    var hiddenTot = jQuery('.reqFamount').val() ;
    jQuery(".totalAmount").val(hiddenTot);
});

定义一个隐藏字段来存储计算值。

<input type="hidden" id="hiddenTotal" />

然后将计算出的值存储到Id为'hiddenTotal'的隐藏字段中。

function updateTotal() {
        var price = 0;

        $(".inputChangeVal").each(function() {
            var t = parseFloat(jQuery(this).val(), 10);
            price = price + t;
        });

        var total = price.toFixed(2);
        $(".totalAmount").val(total);
        $("#hiddenTotal").val(total);
    }

然后当触发返回浏览时,浏览器会自动填充隐藏字段。 接下来检查文件准备好时,读取 hiddenTotal 的值并写入 totalAmount.

$(document).ready(function (){
    // read value and set value of totalAmount to hiddentotal;
    var hiddenTotal = $("#hiddenTotal").val() || 0; //use the hiddenTotal value or if not present set 0 as the default value
    $(".totalAmount").val(hiddentotal)
}

现在 totalAmount 已恢复。这甚至在您离开页面并 return 使用您的浏览器历史记录时也有效。