2013-09-06 3 views
0

동적으로 HTML 콘텐츠를 동적으로로드합니다. 다수의 옵션으로 인해 모든 옵션은 JSON 배열에서 한 번 클라이언트로 전송되므로 클라이언트의 브라우저에 의해 채워 져야합니다. 이 경우, 모든 요소에 이벤트를 첨부하고, <option> 요소를 만들고이 요소 중 하나를 <select> 요소의 기준에 따라 선택합니다.jQuery - 동적으로 추가 된 요소에 대한 DomReady 이벤트

JSFiddle은 select 요소를 클릭하여 원하는 것을 얻을 수있는 방법을 보여줍니다. 그러나 옵션 태그를 만들고 요소가 DOMReady 인 경우 선택한 인덱스를 표시하고 싶습니다. 그러나 해당 이벤트를 찾을 수는 없습니다.

+0

이것은 약간의 장님이지만, [** load event **] (http://api.jquery.com/load-event/)는 어떻습니까? –

+0

불행히도 작동하지 않았다. – doque

+0

'select.append (option) .change (function() {var selectedIndex = $ (this) .children ('selected :)}.); '? – vladkras

답변

0

내가 수동 요소를 추가 할 때 내가 바인딩있어 이벤트를 호출하여 방법을 찾아 관리 click 이벤트를 $ (document)로 보내고 select 자체로는하지 않습니다 (작동하지 않습니다).

감사합니다.

1

대신이 작업을 수행 할 수 있습니다 :

http://jsfiddle.net/LXVhu/2/

은 스토어 그냥 변수에 DOM에 추가 된 요소는,이 변수를 채우는 함수를 호출합니다. 여전히를 바인드해야

// Instead of having to "click" the select fields 
// I'd like to populate the <option> tags everytime a new select item is injected into the DOM. 
$(document).on("click", "select.countrylist", function() { 
    var select = $(this); 
    $(countries).each(function(i) { 
     var option = $("<option></option>").attr("value", this.Key).text(this.Value.EnglishName); 
     if (this.Key === select.data('selected')) option.prop("selected", true); 
     select.append(option); 
     select.get().selectedIndex = i; 
    }); 
}); 
// populate all existing selects 
$("select.countrylist").click(); 

// create new select and populate it 
$('#test').click(function() { 
    var x = $('<select data-selected="USA" class="countrylist"></select>').appendTo("body"); 
    // manually trigger a click which causes populating of select 
    x.click(); 
}); 

See this JSFiddle for a working example

참고 :

function populateSelect(elmt) { 
var select = elmt; 
    $(countries).each(function(i) { 
     var option = $("<option></option>").attr("value", this.Key).text(this.Value.EnglishName); 
     if (this.Key === select.data('selected')) option.prop("selected", true); 
     select.append(option); 
     select.get().selectedIndex = i; 
    });  
} 

$('#test').click(function() { 
    // this select field will not be populated! 
    var elmt = $('<select data-selected="USA" class="countrylist"></select>').appendTo("body"); 
    populateSelect(elmt); 
}); 
0
Change your click handler as follows. 

$('#test').click(function() { 
     // this select field will not be populated! 
     var select = $('<select data-selected="USA" class="countrylist"></select>').appendTo("body"); 


     $(countries).each(function(i) { 
      var option = $("<option></option>").attr("value", this.Key).text(this.Value.EnglishName); 
      if (this.Key === select.data('selected')) option.prop("selected", true); 
      select.append(option); 
      select.get().selectedIndex = i; 
     }); 
    }); 
+0

이것은 코드를 두 배로 만듭니다. 이것은 내가 처음부터 피하고 싶은 코드입니다. – doque

관련 문제