.appendChild() 不是使用 jQuery 时的函数

2022-01-19 00:00:00 function frontend jquery javascript html

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

I am trying to transition from pure JavaScript to jQuery. I have a for loop that dynamically creates HTML elements with data from an API. Here is my old code:

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

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

However, when I transitioned to jQuery and used this instead

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

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

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

I know that .appendChild() isn't jQuery (JS), but shouldn't it still work? Even if I use the jQuery .append() function, I still get an error.

非常感谢任何帮助.

推荐答案

您似乎对互换 jQuery 和 DOM API 感到困惑.它们不能互换使用.document.createElement返回一个 Element$("<div/>") 返回jQuery 对象.Element 对象有 appendChild 方法,jQuery 对象有 append 方法.

You seem to be confusing yourself by inter-changing jQuery and DOM APIs. They cannot be used interchangeably. document.createElement returns an Element and $("<div />") returns the jQuery object. Element object has the appendChild method and jQuery object has the append method.

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

As a good practice, I would suggest you choose between DOM APIs or jQuery, and stick to it. Here is a pure jQuery based solution to your problem

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]);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

相关文章