我有这个代码:
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/