javascript附加奇数输出

时间:2014-10-15 03:53:49

标签: javascript asp.net-ajax

我有一些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>

尼斯。 &lt;选项&gt;很好地嵌套在&lt;选择&gt;。

但是这段代码产生了不同的东西,即使我所做的只是移动&lt;选项&gt;从第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>

联系人选项如何在&lt;&lt;之外结束?选择&gt;,&lt; span&gt;,&lt; div&gt;?或者是让我感到有兴趣的东西&#39;当我到达第3行的末尾时关闭我的开放元素,即使我没有在这些元素中添加内容?

1 个答案:

答案 0 :(得分:1)

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

更好的方法是,为了防止这个问题和效率,要创建你想要添加的整个html字符串,然后立即将它们全部附加。

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

E.g:

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);
}
相关问题