javascript - 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
}
解决方案
我不知道为什么getElementById
在多次尝试后格式化不起作用。我通过使用纯画布 HTML 在其中创建画布来解决问题,text.append
并且它可以工作。
推荐阅读
- excel - VBA - 尝试在选择时动态更改数据验证下拉框输出(崩溃)。Excel 2013
- javascript - 执行 GraphQL 突变时 Firefox 中的 ApolloError
- mysql - SQL - 如果表1中存在id,则将记录插入表2
- python - 参数中带有数字和小数点的函数错误
- android - 如何在 android studio 中修复这个颤振错误?
- spring - Spring Session 更改了 cookie 值,导致后续请求出现 HTTP 302
- google-cloud-platform - 减小 Google 虚拟机 Web 服务器上的磁盘大小
- regex - 如何在 Perl 中从字符串中去除方括号
- python - 为什么 BeautifulSoup 错过了
标签?
- javascript - 不使用多个 ul 列表的滑块