【问题标题】:.appendChild() is not a function when using jQuery.appendChild() 不是使用 jQuery 时的函数
【发布时间】:2017-10-20 13:29:50
【问题描述】:

我正在尝试从纯 JavaScript 过渡到 jQuery。我有一个 for 循环,它使用来自 API 的数据动态创建 HTML 元素。这是我的旧代码:

recipeDiv = [];
recipeDiv[i] = document.createElement("div"); 
recipeDiv[i].setAttribute("class", "recipeBlock");
recipeDiv[i].appendChild(someElement);

但是,当我转换到 jQuery 并改用它时

recipeDiv = [];
recipeDiv[i] = $("<div/>").addClass("recipeBlock");
recipeDiv[i].appendChild(someElement);

我收到以下错误:recipeDiv[i].appendChild 不是函数

我知道 .appendChild() 不是 jQuery (JS),但它不应该仍然有效吗?即使我使用 jQuery .append() 函数,我仍然会收到错误。

非常感谢任何帮助。

【问题讨论】:

  • 使用 $("
    ") 代替 $("
    ")
  • @Lixus 的评论没有任何意义
  • 混合 jQuery 对象和本机 dom 对象时您会感到非常困惑。需要$(recipeContainer).append(recipeDiv[i]);,因为您要附加 jQuery 对象。使用一种方法或另一种方法,但不要混合使用jsfiddle.net/5ozv80dh/1
  • 因为原生dom元素和包裹原生元素的jQuery对象是有区别的

标签: javascript jquery html function frontend


【解决方案1】:

也许 someElement 没有创建?代码是否需要如下?

recipeDiv = [];
var someElement = $("<div/>").addClass("recipeBlock");
recipeDiv[i].appendChild(someElement);

【讨论】:

【解决方案2】:

您似乎对互换 jQuery 和 DOM API 感到困惑。它们不能互换使用。 document.createElement 返回 Element,$("&lt;div /&gt;") 返回 jQuery 对象。 Element 对象具有appendChild 方法,jQuery 对象具有append 方法。

作为一种好的做法,我建议您在 DOM API 或 jQuery 之间进行选择,并坚持下去。这是针对您的问题的纯基于 jQuery 的解决方案

var recipeContainer = $("<div/>")
  .addClass("recipeContainer")
  .appendTo("body");

var recipeDiv = [];
var likes = [];

for (var i = 0; i < 20; i++) {

  //Create divs so you get a div for each recipe
  recipeDiv[i] = $("<div/>").addClass("recipeBlock");

  //Create divs to contain number of likes
  likes[i] = $("<div/>")
    .addClass("likes")
    .html("<b>Likes</b>");

  //Append likes blocks to recipe blocks
  recipeDiv[i].append(likes[i]);

  //Append recipe blocks to container
  recipeContainer.append(recipeDiv[i]);
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 数组也很可能不需要
  • 我也这么认为。但是OP在他的解决方案中有它们。因此,就让他们成为
猜你喜欢
相关资源
最近更新 更多
热门标签