简体   繁体   中英

Accessing Elements returned by Jquery Ajax

Hi I inject a piece of HTML code dynamically inside a DIV on click using Jquery Ajax. After injecting i am not able to select the elements from this injected 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. Can anyone help?

My Jquery Ajax call

$(".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:

.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. Try this:

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

I'm assuming $('#breadcrumb') exists when the DOM loads. Then you just use to filter its descendants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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