javascript - .replacewith 在第二次调用时不起作用

标签 javascript jquery asp.net-mvc signalr

我有以下标记:

    <fieldset>
    <legend>Headline Events...</legend>

    <div style="width:100%; margin-top:10px;">
        <div style="width:100%; float:none;" class="clear-fix">
            <div style="width:400px; float:left; margin-bottom:8px;">
                <div style="width:150px; float:left; text-align:right; padding-top:7px;">
                    &nbsp;Team Filter:&nbsp;
                </div>
                <div style="width:250px; float:left;">
                    <input id="teamFilter" style="width: 100%" />
                </div>
            </div>
            <div style="width:400px; float:left; margin-bottom:8px;">
                <div style="width:150px; float:left; text-align:right; padding-top:7px;">
                    &nbsp;Type Filter:&nbsp;
                </div>
                <div style="width:250px; float:left;">
                    <input id="typeFilter" style="width: 100%" />
                </div>
            </div>
        </div>
    </div>
    <div id="diaryTable" name="diaryTable" class="clear-fix">
        Getting latest Headlines...
    </div>
</fieldset>

我还有以下脚本

<script>

    function teamFilterChange(e) {
        //alert(this.value());
        setCookie('c_team', this.value(), 90);
        $c1 = getCookie('c_team');
        $c2 = getCookie('c_type');
        var param = "true|" + $c1 + "|" + $c2;
        outputHLDiaryEntries(param);
    }

    function typeFilterChange(e) {
        //alert(this.value());
        setCookie('c_type', this.value(), 90);
        $c1 = getCookie('c_team');
        $c2 = getCookie('c_type');
        var param = "true|" + $c1 + "|" + $c2;
        outputHLDiaryEntries(param);
    }

    // This optional function html-encodes messages for display in the page.
    function htmlEncode(value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;
    }

    function outputHLDiaryEntries(param) {
        var url = "Home/DiaryEntries/";
        var data = "id=" + param;
        $.post(url, data, function (json) {
            var n = json.length;
            alert(n + ' ' + json);

            if(n == 0){
                //json is 0 length this happens when there were no errors and there were no results
                $('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");

            } else {
                //json has a length so it may be results or an error message
                //if jsom[0].dID is undefined then this mean that json contains the error message from an exception
                if (typeof json[0].dID != 'undefined') {
                    //json[0].dDI has a value so we
                    //output the json formatted results 
                    var out = "";
                    var i;
                    var a = "N" //used to change the class for Normal and Alternate rows

                    for (i = 0; i < json.length; i++) {

                        out += '<div class="dOuter' + a + '">';
                        out += '<div class="dInner">' + json[i].dDate + '</div>';
                        out += '<div class="dInner">' + json[i].dRef + '</div>';
                        out += '<div class="dInner">' + json[i].dTeam + '</div>';
                        out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
                        out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
                        out += '<div class="dServer">' + json[i].dServer + '</div>';
                        out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';

                        //toggle for normal - alternate rows
                        if (a == "N") {
                            a = "A";
                        } else {
                            a = "N";
                        }
                    }
                    //output our formated data to the diaryTable div
                    $('#diaryTable').replaceWith(out);

                } else {
                //error so output json string
                        $('#diaryTable').replaceWith(json);
                }
            }
        }, 'json');
    }


    $(document).ready(function () {

        //Set User Preferences
        //First check cookies and if null or empty set to default values
        var $c1 = getCookie('c_team');
        if ($c1 == "") {
            //team cookie does not exists or has expired
            setCookie('c_team', 'ALL', 90);
            $c1 = "ALL";
        }

        var $c2 = getCookie('c_type');
        if ($c2 == "") {
            //type cookie does not exists or has expired
            setCookie('c_type', "ALL", 90);
            $c2 = "ALL";
        }

        // create DropDownList from input HTML element
        //teamFilter
        $("#teamFilter").kendoDropDownList({
            dataTextField: "SupportTeamText",
            dataValueField: "SupportTeamValue",
            dataSource: {
                transport: {
                    read: {
                        dataType: "json",
                        url: "Home/SupportTeams?i=1",
                    }
                }
            }
        });
        var teamFilter = $("#teamFilter").data("kendoDropDownList");
        teamFilter.bind("change", teamFilterChange);
        teamFilter.value($c1);

        //typeFilter
        $("#typeFilter").kendoDropDownList({
            dataTextField: "dTypeText",
            dataValueField: "dTypeValue",
            dataSource: {
                transport: {
                    read: {
                        dataType: "json",
                        url: "Home/DiaryTypes?i=1",
                    }
                }
            }
        });
        var typeFilter = $("#typeFilter").data("kendoDropDownList");
        typeFilter.bind("change", typeFilterChange);
        typeFilter.value($c2);

        // Save the reference to the SignalR hub
        var dHub = $.connection.DiaryHub;

        // Invoke the function to be called back from the server
        // when changes are detected
        // Create a function that the hub can call back to display new diary HiLights.
        dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
            // Add the message to the page.
            $('#discussion').append('<li><strong>' + htmlEncode(name)
                + '</strong>: ' + htmlEncode(message) + '</li>');
        };

        // Start the SignalR client-side listener
        $.connection.hub.start().done(function () {
            // Do here any initialization work you may need
            var param = "true|" + $c1 + "|" + $c2;
            outputHLDiaryEntries(param)
        });

    });
</script>

在初始页面加载时,当 signalR 集线器启动时,将调用 outputHLDiaryEntries 函数。如果我随后更改任何下拉列表,则会调用outputHLDiaryEntries,但调用$('#diaryTable').replaceWith();不起作用。如果我刷新页面,就会显示正确的数据。

更新!

根据 A.Wolff 的评论,我通过用我要替换的相同元素包装我需要的内容解决了这个问题...通过在 outputHLDiartEntries 函数的开头添加以下行...

var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';

然后更改每个replaceWith,以便它们包含包装器,例如

$('#diaryTable').replaceWith(outStart + out + outEnd);

最佳答案

replaceWith()替换元素本身,因此下次调用 $('#diaryTable') 将返回空的匹配集。

最好的办法是替换元素的内容,例如:

$('#diaryTable').html("<span>New content</span>");

关于javascript - .replacewith 在第二次调用时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34450386/

相关文章:

Javascript 可以将背景颜色更改为某些 <div>

jQuery Mobile 范围 slider 响应不够

asp.net-mvc - MVC 4 限制所有操作/ Controller ,除非管理员或角色/用户允许

c# - mvc c# 中的安全 id 值

javascript - 根据下拉选择更改单选按钮的值

javascript - 访问数组值返回 'undefined' ,但我可以使用 console.dir() 查看这些值?

javascript - VueJS不在 Electron 应用程序内部的DOM上呈现数据

jquery - 流程图条形宽度

jquery - 为什么 Ajax.BeginForm 返回另一个页面中的部分 View

asp.net-mvc - 使用 RedirectToAction 时 View 上的模型为空