2013-12-14 53 views
1

監聽器+ jQuery對象+觸發變化ebent +追加監聽器+ jQuery對象+觸發更改事件+追加

我想:

  1. 設立監聽
  2. 定義HTML選項框
  3. 將html轉換爲jquery對象
  4. 觸發更改事件 - 觸發列表器
  5. 將結果附加到現有的DOM元素牛逼

這一步#4的工作不

// add listener on change in options 
$('.cl_preAction').on("change",function(){     
    alert(""); 
})' 

// set up html string with options 
    glCfgSection = <select name='ACTC' class='cl_preAction' id='cl_preAction' data-theme='a'>\n\ 
     <option data-location='T' value='001'>Option 1</option>\n\ 
     <option data-location='T' value='002'>Option 2</option>\n\ 
     <option data-location='T' value='003'>Option 3</option>\n\ 
     <option data-location='T' value='004'>Option 4</option>\n\ 
    </select>\n\"; 

    // convert string to jquery object 
    myTmpl = $(glCfgSection); 

    // trigger a change event - neither of these seem to work 
    //$('.cl_preAction option', myTmpl).change();    
    $('.cl_preAction option', myTmpl).trigger('change');   

    // append to page (jQuery Mobile) 
    myTmpl.appendTo("#placeholder"+glCurrentTab).trigger('create'); // this works 
+0

如果您需要直接調用,爲什麼不把多餘的功能,甚至調用從改變該函數當你需要時,你可以直行。 – Hardy

回答

2

有2種變化,你將不得不作出。

  1. 因爲要創建動態元素,你需要使用基於事件委派處理
  2. 由於事件委派用於註冊到祖先元素的處理程序,因此事件觸發將調用處理程序只有在元素添加到DOM結構

嘗試

// use event delegation to handle dynamic elements 
$(document).on("change",'.cl_preAction', function(){     
    alert(""); 
}); 

// set up html string with options 
glCfgSection = "<select name='ACTC' class='cl_preAction' id='preAction' data-theme='a'>\n\ 
<option data-location='T' value='001'>Option 1</option>\n\ 
<option data-location='T' value='002'>Option 2</option>\n\ 
<option data-location='T' value='003'>Option 3</option>\n\ 
<option data-location='T' value='004'>Option 4</option>\n\ 
</select>\n"; 

// convert string to jquery object 
myTmpl = $(glCfgSection);  

// append to page (jQuery Mobile) 
//fire the event after adding the element to dom because the listener is added to the document object 
myTmpl.appendTo("#placeholder"+glCurrentTab).trigger('change').trigger('create'); // this works (edited string delimiters) 
+0

輝煌!我本來可以花一整天的時間看這個! – george