Jquery并向表中添加行
我有以下jquery代码。
var destTable = $("#numbers"); $(document).ready(function() { $("#btnAdd").click(function() { //Take the text, and also the ddl value and insert as table row. var newRow = $("hi "); $("#numbers").append(newRow); }); });
我真正想要的是存储一个元素的引用,然后从那里使用它。
上面的代码按预期添加了一行到我的表,但如果我使用。 $(destTable).append(newRow)
或destTable.append(newRow)
没有任何事情可以让任何人对我destTable.append(newRow)
了解吗?
谢谢
在document.ready中保留引用:
$(document).ready(function() { var destTable = $("#numbers"); $("#btnAdd").click(function() { //Take the text, and also the ddl value and insert as table row. var newRow = $("hi "); $("#numbers").append(newRow); }); });
document.ready的意思是等待DOM准备好; 如果你尝试做$('#numbers');
在它之外(并且代码不会出现在文档中的元素之后),DOM将不会创建此元素,因此您将无法正确引用它。
一旦你这样做,你应该能够做到:
destTable.append(newRow);
在click
function里面。 然而,作为最后一个注释,使用$
表示jQuery集的变量是一个常见且公认的惯例。 所以这是最好的:
var $destTable = $("#numbers");
你可以像这样使用appendTo:
$("Hello ").appendTo("#MyTable > tbody")