簡體   English   中英

Javascript-輸入不保留值?

[英]Javascript - Input not Keeping Values?

我的桌子在剃刀產生的View 搜索框允許用戶通過將AJAX請求發布到指定的控制器來執行(您猜對了)搜索操作。 返回的結果是PartialView(包含新表+分頁器),我用它替換了現有的table + pager。

還有一個按鈕可以向表中添加行(具有兩個輸入字段和一個保存按鈕)。 我想在執行搜索之前在本地“持久化”這些行,然后一旦從AJAX請求獲得結果,便將它們附加回表中。

在我的腳本中,您可以看到我找到了所有“未保存”的行(類.new-element-row )並將它們添加到數組中,然后發送搜索請求。 然后,在用新表替換現有表之后,我將它們再次追加到表中:

newElements = new Array(); // unsaved rows

$(document).ready(function () {

        $('#searchbox').keyup(function () {

            var keyWords = $("#searchbox").val();

            ////////////////////////////////////////////////
            // Persist the non-saved rows///////////////////
            $("tr.new-element-row").each(function () {
                $this = $(this);
                var elem = $this[0];
                newElements.push(elem);
            });
            ////////////////////////////////////////////////

            // Send the search request
            $.ajax({
                url: '@(Url.Action("ActionName", "ControllerName"))',
                data: 'searchString=' + keyWords,
                cache: false,
                success: function (html) {

                    // Replace table with the one from the search results
                    $("#tableContainer").html(html);

                    ////////////////////////////////////////////////
                    // Re-append the unsaved rows to the new table//
                    newElements.forEach(function (entry) {
                        $("#table").append(entry.outerHTML);
                    });
                    ////////////////////////////////////////////////

                    // Clear...
                    newElements = new Array();
                    (...)
                }
            });

        });
});

如果不是因為重新添加的行的輸入字段不保留我輸入的文本,它幾乎可以很好地工作(即,保存並再次添加行)。

我究竟做錯了什么? 我可能缺少明顯的東西,但是我找不到它。

問題在於您不推回元素本身,而是推回HTML。 如果您在文本輸入中輸入內容,則其HTML代碼不會更改,盡管DOM對象肯定會更改。

不知道為什么在這里使用outerHTML ,但是似乎最簡單的解決方法是刪除它,然后追加元素:

newElements.forEach(function (entry) {
    $("#table").append(entry);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM