2014-05-16 71 views
0

工作我有使用jQuery新创建的元素的问题我的小脚本是在这里:jQuery选择不添加上标签

$('.view_button').click(function(){ 

    $.ajax({ 
     url: '/devices/view_ajax', 
     cache: false, 
     type: 'post', 
     dataType: 'JSON', 
     data: {id: $(this).attr('data')}, 
     success: function(data){ 
      var maskHeight = $(window).height(); 
      var maskWidth = $(window).width() - 100; 
      var body = $('#devices_wrapper'); 
      var div_outside = $('<div/>', {id:'wrapper'}).appendTo(body); 
      div_element = $('<div/>', {id:'popup'}).appendTo(div_outside); 
      div_element.css({position: 'relative', bottom: 0, 'z-index': 10000}); 
      $.each(data, function(i,v){ 
       if(v && i){ 
        div_wrapper = $('<div/>', {'class': 'part'}).appendTo(div_element); 
        div = document.createElement('div'); 
        span = document.createElement('span'); 
        $(span).html(i).appendTo(div_wrapper); 
        $(div).html(v).appendTo(div_wrapper); 
       } 
      }); 
      close_button = $('<div/>', {'class':'close_popup', text: 'X'}).appendTo(div_wrapper); 

     }, 
     error: function(data){ 
      alert('error'); 
     } 
    }) 
}); 

$('.close_popup').click(function(){ 
    $('#wrapper').remove(); 
}) 

当我执行上close_popup没有点击,我认为它的原因是那tag > close_popup是不是被jQuery选择器看到的,如果是的话如何添加它?或者,也许有不同的我的错误

回答

1

您需要使用event delegation附加事件动态添加到DOM的元素:

$(document.body).on('click','.close_popup',function(){ 
    $('#wrapper').remove(); 
}) 
+0

作品,谢谢:D – Viszman

1

使用delegeateon绑定动态创建的元素事件。

$(document).delegate('.close_popup','click',function(){ 
    $('#wrapper').remove(); 
}); 

OR

$(document).on('.close_popup','click',function(){ 
    $('#wrapper').remove(); 
}); 

但它始终是更好地使用.on

1
Try select immediate parent which static on your html dom 


$("#devices_wrapper").on("click",".close_popup",function(){ 

      $('#wrapper').remove(); 
    });