访问Jquery Ajax返回的元素

时间:2014-09-26 10:00:33

标签: javascript jquery html ajax

您好我在点击时使用Jquery Ajax在DIV中动态注入一段HTML代码。注入后,我无法从这个注入的HTML中选择元素。我需要为这些元素编写click事件来更改主页面上的一些数据。如果我写内联jquery我无法访问主页上的元素。有人可以帮忙吗?

我的Jquery Ajax调用

$(".template-2-column-std a").not('.emptyMessage').click(function () {        
    var parentidVal = $(this).data('parentid')
    $.ajax({
        url: '/Navigation/GetBreadCrumbList',
        contentType: 'application/html; charset=utf-8',
        data: { id: parentidVal },
        type: 'GET',
        dataType: 'html'
    })
    .success(function (result) {
        $('#breadcrumb').html(result);
    })
    .error(function (xhr, status) {
        alert(status);
    })
});

3 个答案:

答案 0 :(得分:0)

尝试

$('body').on('click','#myDiv',  function(){ 


});

而不是

 $("#myDiv").click ...

这是访问动态生成元素的方式。

答案 1 :(得分:0)

您应该在succes函数中绑定事件,例如:

.success(function (result) {

    $('#breadcrumb').html(result);
     bindEventListener();
})
function bindEventListener(){
  $("#newAddedElement").on('click', function(){
     do somethins...
  })
}

答案 2 :(得分:0)

您需要使用事件委派将事件侦听器附加到加载文档时不在DOM上的元素。试试这个:

$('#breadcrumb').on('click', <selector>, function() {...});

我假设DOM加载时存在$('#breadcrumb')。然后你只是用来过滤它的后代。