使用jQuery时.appendChild()不是函数 [英] .appendChild() is not a function when using jQuery

查看:45
本文介绍了使用jQuery时.appendChild()不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从纯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>

这篇关于使用jQuery时.appendChild()不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆