首页 > 解决方案 > 更新动态生成元素的属性

问题描述

嗯,大家好,所以我在更新一些动态生成元素的属性时遇到了问题。问题是,它们不是完全使用 javascript DOM 动态生成的,例如'document.createElement("image")',而是我有两个小的 .PHP 文件,它们已经包含所有标签和元素(带有 .classes 和 #ID 用于 stylng等)必须显示,并且当发生适当的点击时,任一文件都被“加载”到指定的 DIV 内,ID 为“DIV_load_aceptor”。还要增加难度(?),甚至 Buttons_1 和 _2 以及 #DIV_load_aceptor 都是动态生成的。(同样,一个文件被加载到“超级 div”中。

考虑中的动态生成(而不是 .load()-ed)HTML 段是:

<button id="Button_1">Image</button>
<button id="Button_2">Data</button>

<DIV id="DIV_load_aceptor">
    // PHP Files are loaded here
</DIV>

将被加载的两个 PHP 文件是:

<DIV id="Image_Container">                 //1. FILE_IMAGE.PHP
    <img id="First_Image" src="">
    <label id="filename"></label>
    <label id="filetype"></label>
    <label id="filesize"></label>
</DIV>
<DIV id="User_Container">                 //2. FILE_USER.PHP      
    <img id="Another_Image" src="">
    <label id="Username"></label>
    <label id="USertype"></label>
    <label id="Useremail"></label>  
    //more elements, could be anything, this is just a simple example.  
</DIV>

Jquery/Javascript 组合是

$("#Button_1").click(function(){
    $("#DIV_load_aceptor").load("FILE_IMAGE.PHP");
    
    aj = new XMLHttpRequest();  ///ajax to get some more details for attributes     
    {//aj readystate checks 
                
        var DATA_ = JSON.parse(aj.responseText);
        $("#First_Image").attr("src", DATA_.IMG_SRC);
        $("#filesize").html(DATA_.IMG_SIZ); 

        //etc etc
    }
    aj.open("post", "DATABASE_QRY_IMG_details_Json_return",true);
    aj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    aj.send(some data);
});

$("#Button_2").click(function(){
    $("#DIV_load_aceptor").load("FILE_USER.PHP");
    
    aj = new XMLHttpRequest();  
    {   var DATA_  = JSON.parse(aj.responseText);
        $("#Another_Image").attr("src", DATA_.IMG_SRC);
        $("#Username").html(DATA_.UNAME);
        
        //etc etc
    }
    aj.open("post", "DATABASE_QRY_USER_Json_return",true);
    aj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    aj.send(some data);
});

毫不奇怪,它不起作用.. 小 PHP 文件中的元素和标签的属性没有更新。问题是,PHP 小文件中的标签非常多(上面的代码只是说明问题的压缩版本。)这就是为什么如果我继续使用 javascript 逐个创建它们将需要相当长的时间(并变得乏味)。有没有办法更新这些元素属性?从文件加载元素时,如何将元素附加到 DOM?

标签: javascripthtmljquerydomdynamically-generated

解决方案


推荐阅读