jQuery Jquery并向表中添加行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1067828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:33:46  来源:igfitidea点击:

Jquery and adding row to table

jquery

提问by RubbleFord

I have the following jquery code.

我有以下 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 = $("<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.

我真正想要的是存储对元素的引用一次,然后从那里使用它。

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?

上面的代码按预期将一行添加到我的表中,但如果我使用。$(destTable).append(newRow)或者destTable.append(newRow)什么也没有发生,有人能帮我解释一下吗?

Thanks

谢谢

回答by Paolo Bergantino

Keep the reference inside document.ready:

将引用保留在 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);
  });
});

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.

document.ready 的意义在于等待 DOM 准备就绪;如果您尝试在$('#numbers');它之外执行(并且代码没有出现在文档中的元素之后),DOM 将尚未创建此元素,因此您将无法正确引用它。

Once you do this, you should be able to do:

完成此操作后,您应该能够执行以下操作:

destTable.append(newRow);

Inside the clickfunction. 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:

click函数内部。然而,最后要注意的是,在代表 jQuery 集的变量前面加上一个$. 所以这是最好的:

var $destTable = $("#numbers");

回答by benahm

Your can use appendTo like this :

您可以像这样使用 appendTo :

$("<tr><td>Hello</td><tr>").appendTo("#MyTable > tbody")