javascript附加奇数输出

javascript append odd output

本文关键字:输出 javascript      更新时间:2023-09-26

我有一些JavaScript AJAX函数,它应该在发生某些事情时重写页面的一部分。它工作得很好。。。只是我告诉它写在章节里的内容并不总是出现在页面上。

例如:这段代码输出了我所期望的,一个包含一个项目的下拉列表

function(response) {
    $('#serverSelection').html('');
    $('#serverSelection').append('<div class="form-group"><label class="control-label col-md-2" for="ServerList">Assign the Sentinel to a Server</label><span class=" col-md-10"><select class="form-control" id="SentinelServerId" name="SentinelServerId"><option value="Contact">Contact</option>');        
    $('#serverSelection').append('</select></span></div>');
}

以及预期输出

<span class="form-group" id="serverSelection">
    <div class="form-group">
        <label class="control-label col-md-2" for="ServerList">Assign the Sentinel to a Server</label>
        <span class=" col-md-10">
            <select name="SentinelServerId" class="form-control" id="SentinelServerId">
                <option value="Contact">Contact</option>
            </select>
        </span>
    </div>
</span>

不错。<option>很好地嵌套在<选择>。

但是这个代码产生了一些不同的东西,即使我所做的只是移动<option>元素从第3行末尾到第4行自己的.append()。

function(response) {
    $('#serverSelection').html('');
    $('#serverSelection').append('<div class="form-group"><label class="control-label col-md-2" for="ServerList">Assign the Sentinel to a Server</label><span class=" col-md-10"><select class="form-control" id="SentinelServerId" name="SentinelServerId">');
    $('#serverSelection').append('<option value="Contact">Contact</option>');
    $('#serverSelection').append('</select></span></div>');
}

这就是它所产生的。我真的希望和第一个(正确的)输出完全一样。

<span class="form-group" id="serverSelection">
    <div class="form-group">
        <label class="control-label col-md-2" for="ServerList">Assign the Sentinel to a Server</label>
        <span class=" col-md-10">
            <select name="SentinelServerId" class="form-control" id="SentinelServerId"></select>
        </span>
    </div>
    <option value="Contact">Contact</option>
</span>

Contact选项是如何在<选择>,<span>和<div>?或者,当我到达第3行的末尾时,有什么东西关闭了我的开放元素,即使我还没有完成在这些元素中添加东西,这是在帮我一个"忙"吗?

我认为这是因为jQuery在每次调用append时都会自动附加结束标记。

为了防止这个问题并提高效率,最好的方法是创建要添加的整个html字符串,然后一次将它们全部追加。

jsfiddle:http://jsfiddle.net/xc2hpwa2/

例如:

function (response){
    var html = '';
    html += '<div class="form-group"><label class="control-label col-md-2" for="ServerList">Assign the Sentinel to a Server</label><span class=" col-md-10"><select class="form-control" id="SentinelServerId" name="SentinelServerId">';
    html +='<option value="Contact">Contact</option>';
    html += '</select></span></div>';
    $('#serverSelection').html(html);
}