jQuery并将行添加到表 [英] Jquery and adding row to table
问题描述
我有以下jquery代码.
I have the following jquery code.
var destTable = $("#numbers");
$(document).ready(function() {
$("#btnAdd").click(function() {
//Take the text, and also the ddl value and insert as table row.
var newRow = $("<tr><td>hi</td></tr>");
$("#numbers").append(newRow);
});
});
我真正想要的是存储一次对元素的引用,然后在该元素上使用它.
What I would really like is to store a reference to an element once and then use it from there on it.
上面的代码按预期但在我的表中添加了一行,如果我使用的话. $(destTable).append(newRow)
或destTable.append(newRow)
什么都没有发生,谁能为我提供任何启示?
The code above add's a row to my table as expected but if I use. $(destTable).append(newRow)
or destTable.append(newRow)
nothing happens could anyone shed any light on this for me?
谢谢
推荐答案
将引用保留在document.ready中:
Keep the reference inside 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 = $("<tr><td>hi</td></tr>");
$("#numbers").append(newRow);
});
});
document.ready的重点是等待DOM准备就绪;如果尝试在其外部执行$('#numbers');
(并且代码未出现在文档中的元素之后),则DOM尚未创建此元素,因此您将无法对其进行适当的引用.
The point of document.ready is to wait for the DOM to be ready; if you try doing $('#numbers');
outside of it (and the code does not appear after the element in the document) the DOM will not have yet created this element so you won't have a proper reference to it.
执行此操作后,您应该可以执行以下操作:
Once you do this, you should be able to do:
destTable.append(newRow);
在click
函数内部.但是,最后要注意的是,使用$
开头表示jQuery集的变量是一种常见且可接受的做法.所以这是最好的:
Inside the click
function. As a last note, however, it is a common and accepted practice to preface variables that represent jQuery sets with a $
. So this is best:
var $destTable = $("#numbers");
这篇关于jQuery并将行添加到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!