2014-10-15 2 views
0

무언가가 발생했을 때 내 페이지 섹션을 다시 작성해야하는 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> 

니스. < 옵션>은 < select> 내부에 멋지게 중첩되어 있습니다.

그러나이 코드는 뭔가 다른 것을 만듭니다. 심지어 내가 한 것은 < 옵션> 요소를 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> 

어떻게 연락 옵션은 < DIV>은 < 선택>의 < SPAN> 외부 바람 및습니까? 아니면 내가 그 요소의 내부에 물건을 추가하지 않았어도 내가 3 행 끝 부분에 도달 할 때 내 열린 요소를 닫음으로써 나에게 '호의'를하는 것이 무엇입니까?

답변

1

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); 
}