jquery - 为什么 jQuery.append(new Array(3).fill($ ('<div>' ,{text :'hello' }))) 仅附加一项?

标签 jquery html arrays

我有这个代码:

const a = [
  $('<div>', { text:'hello' }), 
  $('<div>', { text:'hello' }),
  $('<div>', { text:'hello' })
]
$('#a').append(a)

我得到了预期的结果,3 个新项目附加到 #a

但是,当我以这种方式创建数组时,我只会将 1 个项目附加到 #b

const b = new Array(3).fill($('<div>', { text: 'hello' })) 
$('#b').append(b)

在控制台输出中,2 个数组看起来相同。玩转:JS Bin

const a=[
  $('<div>',{text:'hello'}),
  $('<div>',{text:'hello'}),
  $('<div>',{text:'hello'})]
const b=new Array(3).fill($('<div>',{text:'hello'}))
$('#a').append(a)
$('#b').append(b)
console.log('Array.isArray(a): '+Array.isArray(a)+' a.length: '+a.length)
console.log('Array.isArray(b): '+Array.isArray(b)+' b.length: '+b.length)
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Append</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <div id="a" style="background:aqua;"></div>
  <div id="b" style="background:silver;"></div>
</body>
</html>

最佳答案

你用三倍相同的对象引用填充数组,这意味着 jQuery 只会添加一次。第二次和第三次它会认为它已经添加并且不做任何事情。

改变:

const b = new Array(3).fill($('<div>', { text: 'hello' })) 

到:

const b = Array.from(Array(3), () => $('<div>', { text: 'hello' })) 

现在您有一个执行了三次的回调,因此调用了三次 $(...) 而不是一次,从而创建了三个独立的实例。

关于jquery - 为什么 jQuery.append(new Array(3).fill($ ('<div>' ,{text :'hello' }))) 仅附加一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51537127/

相关文章:

html - 另一个元素内的 css 选择器

c++ - 在线法官不接受代码

html - 如何让我的文字高于我的 img <div>?

c - 如何将二维数组传递给带有行偏移量的函数,如 C 中的 M*i ?

python - 对 NumPy 数组的一行求和

javascript - 更改每个选项值 javascript/jQuery

php - jQuery 更新值未获得新值

javascript - 音乐播放器跳过向前/向后功能 JQuery

javascript - 如何在列表项旁边的垂直线上均匀对齐复选框?

html - 如何防止图片溢出到div中?