簡體   English   中英

ajax 未將 html 更新為 javascript 動態創建的 div

[英]ajax not updating html into javascript-dynamically created div

(使用 jQuery)

1)我有一個點擊 javascript 創建一個帶有下拉和 div 的表單,如下所示:

$('#closestDiv').on('click','.firstClick', function(event){

var pass = $(this).attr('data-pass');

var f = document.createElement("form");
    f.setAttribute('method',"post");
    f.setAttribute('id',"newForm");
    f.setAttribute('action',"SubmitForm.php");

    var d = document.createElement("select");   
        var op1 = new Option();
            op1.value = "1";
            op1.text = "1"; 
            op1.setAttribute('class', "secondClick");
            op1.setAttribute('data-pass', pass);        
        d.options.add(op1);

f.appendChild(d);

var div = document.createElement("div");
        div.setAttribute('id', "newDiv");
        div.innerHTML = 'REPLACE CONTENT';      

f.appendChild(div);

$("#closestDiv").append(f);

 }); // end on click

2)然后我有一個 onclick 用於下拉選項,通過 ajax 將內容加載到所述 div 中。

$('#closestDiv').on('click', '.secondClick', function () {  
    $(this).prop('selected', true);
    var value = $(this).attr('value');
    var pass = $(this).attr('data-pass');

$.ajax({
          url: 'getContent.php',
          type: "get",
          data : {value: value, pass: pass},
        success: function(response){

         var result = JSON.parse(response);      

        $('#newDiv').html(result['newContent']);

        console.log(result['newContent']);      
        console.log($('#newDiv'));

            } // end success function
    }); // end ajax call

 }); // end on click

控制台顯示正確的 newContent 正在傳遞,並且在控制台中,div 元素顯示正確的 html 和 newContent,但實際頁面 div 仍顯示“REPLACE CONTENT”(即未更新)。

當下拉列表與頁面一起加載而不是通過 javascript 加載時,我已經成功完成了此操作。 我想知道我是否不了解 DOM 加載事物的順序,以及如何使其工作。 出於某種原因,我認為如果我在 javascript 中構建下拉列表(而不是通過 ajax - 它幾乎給出了相同的結果,如果修復相同,我更喜歡它......)它會立即起作用。

我還注意到下拉菜單沒有顯示已選擇的內容,即使正確選擇的選項正在傳遞給 ajax。

任何指針最受贊賞。 謝謝!

下面替換為:

$('#newDiv').html(result['newContent']);

和:

$(document).find('#closestDiv #newDiv').html(result['newContent']); 

當 DOM 動態更新時,您需要訪問與文檔相關的添加元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM