简体   繁体   English

访问Jquery Ajax返回的元素

[英]Accessing Elements returned by Jquery Ajax

Hi I inject a piece of HTML code dynamically inside a DIV on click using Jquery Ajax. 嗨,我使用Jquery Ajax在点击时在DIV中动态注入了一段HTML代码。 After injecting i am not able to select the elements from this injected HTML. 注入后,我无法从注入的HTML中选择元素。 I need to write click events for these elements to change some data on the main page. 我需要为这些元素编写单击事件,以更改主页上的某些数据。 If i write jquery inline i am not able to access the elements on the main page. 如果我以内联方式编写jQuery,则无法访问主页上的元素。 Can anyone help? 有人可以帮忙吗?

My Jquery Ajax call 我的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);
    })
});

Try 尝试

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


});

instead of 代替

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

It's the way to access elements dynamically generated. 这是访问动态生成的元素的方式。

You should bind you events in succes function, like: 您应该在succes函数中绑定事件,例如:

.success(function (result) {

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

You need to use event delegation to attach event listeners to elements that weren't on the DOM when the document loaded. 您需要使用事件委托将事件侦听器附加到文档加载时不在DOM上的元素上。 Try this: 尝试这个:

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

I'm assuming $('#breadcrumb') exists when the DOM loads. 我假设在加载DOM时存在$('#breadcrumb')。 Then you just use to filter its descendants. 然后,您仅用于过滤其后代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM