开发者

JQuery ajax can't find elements in returned HTML

开发者 https://www.devze.com 2023-01-18 16:04 出处:网络
I have a simple $.ajax({ url: someUrl, method: \'get\', dataType: \'html\', success: function(data) {

I have a simple

$.ajax({
 url: someUrl, 
 method: 'get',
 dataType: 'html',
 success: function(data) { 
    开发者_高级运维        $('#someId').append($(data));
          } 
 });

The problem is I can't find elements simply within the returned data. If there's an input with id="myInput" I can't get it with $('#myInput') or $('input[id=myInput]'). I CAN find it with:

$('input').each(function(i,e){ if($(e).attr('id') == 'myInput'){ doStuff(e); } });

But who wants to do that each time? I saw this question but the solutions provided didn't work for me. In addition to what's up there I've tried

$('#someId').html(data);
$(data).appendTo($('#someId'));

and I'm using jQuery 1.4.2. Thoughts, suggestions?


I think what you are trying to do is access a element in the DOM that you haven't yet attached to the DOM. Until you $(someElement).html(data) or append it somewhere, it's just a data return object and not yet part of the DOM.

Also, consider using getJSON to get the data back as JSON (encode it as JSON on the remote end by putting it in an array in PHP and doing echo json_encode($array);
then you can access each item by it's array name, as data.NAME and assign it to parts of your DOM.


The only cause of this I can think of is that your HTML syntax is malformed somewhere. Try taking out chunks of code in front of and after your myInput element and keep doing so until it functions as expected. Then slowly put pieces back in until you can identify exactly where the issue is.


Here is my function:

$.ajax({
        type: 'POST',
        url: direccion_url,
        dataType: 'html',
        success: function(datos){
                $('#panel_salida').html(datos);
                $('#panel_salida').find('#apelli1_txt').val('valor');
        }
});

I hope it helps you.


If you really need to do this (not sure why) then use .find on the returned data

so in your success function something like

success: function(data) {
  $(data).find("#inputId").doSomething();
  $('#someId').append(data);
} 

FatherStorm is probably right, if you're doing an append, then just searching the whole dome using $("#inputId"), it probably just doesn't exist in the DOM yet.

0

精彩评论

暂无评论...
验证码 换一张
取 消