首页 > 解决方案 > AJAX成功内的动态appendChild

问题描述

我是网络开发的新手。

我已经从 ajax 成功函数中渲染了文本。我想在每个文本行下添加画布。

在 AJAX 成功中,我尝试了以下两个,文本成功呈现,文本 id 成功动态分配,但它们都失败了Cannot read property 'appendChild' of null,我认为有问题,document.getElementById('result'+idx).appendChild(canv);好像我使用document.body.appendChild(canv);我得到了画布但不在所需的位置。

我不知道为什么getElementById会为空,我也尝试'result'+idx.toString()过,但它也不起作用。

$.each(cat_result, function(idx, value) { 
text.append('<id="result'+idx+'">'+'<br>');
canvas_and_plot(idx,cat_result[idx][8],cat_result[idx][9],cat_result[idx][10])
});
$('#result').replaceWith(text);
$.each(cat_result, function(idx, value) { 
text.append('<id="result'+idx+'">'+'<br>');
});
$('#result').replaceWith(text);
$.each(cat_result, function(idx, value) { 
canvas_and_plot(idx,cat_result[idx][8],cat_result[idx][9],cat_result[idx][10])
});

HTML

<p class="result-box" id="result-box">The result is : <br><strong id="result"></strong></p>

JS函数

function canvas_and_plot(idx,a,b,c) {
var canv = document.createElement("canvas");
canv.width = 200;
canv.height = 200;
canv.setAttribute('id', 'canv_'+idx);
canv.style.position = 'relative';
canv.style.float = 'left';
document.getElementById('result'+idx).appendChild(canv); // Cannot read property 'appendChild' of null
//other code that does the plotting
}

标签: javascriptjqueryajax

解决方案


我不知道为什么getElementById在多次尝试后格式化不起作用。我通过使用纯画布 HTML 在其中创建画布来解决问题,text.append并且它可以工作。


推荐阅读