listener + jquery对象+触发器更改事件+追加

时间:2013-12-14 01:08:05

标签: jquery append listener

listener + jquery object + trigger change ebent + append

我想:

  1. 设置监听器
  2. 定义HTML选项框
  3. 将html转换为jquery对象
  4. 触发更改事件 - 触发列表器
  5. 将结果附加到现有DOM元素
  6. 这一步#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
    

1 个答案:

答案 0 :(得分:2)

您必须进行2项更改。

  1. 由于您正在创建动态元素,因此需要使用基于事件委派的处理程序
  2. 由于使用了事件委托,处理程序被注册到祖先元素,因此仅当元素添加到dom结构时,事件触发才会调用处理程序
  3. 尝试

    // 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)