我有以下由下面的 Javascript 代码动态生成的 html,
<tbody>
<tr class="student">
<td class="missed-col">0</td>
</tr>
</tbody>
生成上面 html 的代码,
var $tbody = $('tbody');
var $row = $('<tr></tr>').addClass('student');
var $nameCol = $('<td></td>').addClass('name-col').text(name);
var $missedCol = $('<td></td>').addClass('missed-col').text('0');
$row.append($nameCol);
$row.append($missedCol);
$tbody.append($row);
然后,我想在 Missed-col 类之前再插入一行。由于某种原因,我无法在上面的代码中引用 $missedCol,因为代码跳转到不同的功能 block 。所以,我做了以下事情,
$('<td class="attend-col"><input type="checkbox"></td>').insertBefore($('tbody tr .missed-col'));
但是,它不起作用。我发现原因是 jQuery 无法以这种方式选择动态生成的元素。我在网上发现了一些类似的问题,但找不到好的答案。
最佳答案
尝试将选择器传递给 insertBefore()
而不是传递 jquery
对象,因为这有点过分了。
HTML 代码:
$('<td class="attend-col">3</td>').insertBefore('tbody tr .missed-col');
关于javascript - jQuery,如何选择动态生成的html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41276849/