简体   繁体   English

识别 AJAX 请求后添加到 DOM 的新元素

[英]Recognize new elements added to DOM after AJAX request

I am trying to display a new div element added to the DOM via AJAX.我正在尝试显示通过 AJAX 添加到 DOM 的新 div 元素。

So, via AJAX/PHP I added dynamically some new buttons因此,通过 AJAX/PHP,我动态添加了一些新按钮

<button type="button" id="viewPP_'.$index.'" onclick="viewPP('.index.')">View</button>

And also added dynamically some new hidden divs并且还动态添加了一些新的隐藏 div

<div id="viewPP_'.$index.'" style="display: none;">

In my main page I have a JS function (before the $(document).ready) to show/hide the div在我的主页中,我有一个 JS function(在 $(document).ready 之前)来显示/隐藏 div

function viewPP(i){
    
var obj = "viewPP_"+i;
    
document.getElementById(obj).style.display = "block";
//$(obj).toggle();

}    

If I use document.getElementBy... , nothing happens.如果我使用document.getElementBy... ,什么也不会发生。 (no error, just do nothing) (没有错误,什么都不做)

If I use $(obj) , nothing happens (no error, just do nothing)如果我使用$(obj) ,什么都不会发生(没有错误,什么都不做)

I can understand new elements added to the DOM after the page is loaded are not recognized by JQuery, but can't find the way to make it work.我可以理解 JQuery 无法识别页面加载后添加到 DOM 的新元素,但找不到使其工作的方法。

How can I do that??我怎样才能做到这一点??

Remove that #, when declaring obj.在声明 obj 时删除该 #。 When you are using getElementById method, you just need to specify id, without #, as you would use in CSS or querySelector method.当您使用 getElementById 方法时,您只需要指定 id,不带 #,就像您在 CSS 或 querySelector 方法中使用的那样。

function viewPP(i){
    
var obj = "viewPP_"+i;
    
document.getElementById(obj).style.display = "block"

}    

If this is not it, there is something going on with loading these elements...如果不是这样,那么加载这些元素会发生一些事情......

One approach could be that, you can add a fix dpm element which can act as parent dom element for your dynamic dom element.一种方法可能是,您可以添加一个修复 dpm 元素,该元素可以充当动态 dom 元素的父 dom 元素。 By this approach you can fetch child nodes of fixed dom parent node.通过这种方法,您可以获取固定 dom 父节点的子节点。

I noticed the buttons and divs had the same id, so I fixed them and now work.我注意到按钮和 div 具有相同的 id,所以我修复了它们,现在可以工作了。

Here's the working code, hope it helps someone in the future.这是工作代码,希望它对将来的人有所帮助。

Thanks everyone for your help!感谢大家的帮助!

JS JS

function viewPP(i){   
  var obj = "#dataPP_"+i;
  $(obj).toggle();
} 

$(document).ready(function(){
    $.ajax({
       ...
    });
});

PHP Response to AJAX Request PHP 对 AJAX 请求的响应

print '<button type="button" id="viewPP_'.$index.'" onclick="viewPP('.index.')">View</button>';

print '<div id="dataPP_'.$index.'" style="display: none;"></div>';

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

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