jQuery 在附加新元素之前填充内容
我正在尝试用数据填充featured
,然后将其附加到#wrapper。这对我不起作用。我做错了什么?
var featured = '<div id="featured"></div>';
$('#imageTable tbody tr td img').each(function(){
$(featured).append($(this).attr('src'));
});
$(featured).appendTo('#wrapper');
I'm trying to populate featured
with data then append it to #wrapper. This isn't working for me. What am i doing wrong?
var featured = '<div id="featured"></div>';
$('#imageTable tbody tr td img').each(function(){
$(featured).append($(this).attr('src'));
});
$(featured).appendTo('#wrapper');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
说明:
当您在循环
$(featured)
中执行此操作时,它会为每个选定元素创建一个新的 div,因此只有最后一个 div 会附加到您的#wrapper
。您需要在each
循环之外创建 jQuery 对象。Explaination:
When you do this inside the loop
$(featured)
, it creates a NEW div for each selected element, so only the last div will be appended to your#wrapper
. You need to create the jQuery object outside of theeach
loop.这是因为循环内有
$(featured)
调用。您只想调用它一次。试试这个:
It's because you have the
$(featured)
call inside the loop. You only want to call it once.Try this:
与 Bryan Ross 非常相似,只是以更有效的方式创建 div。它可能不是那么简单,但我相信它的性能更高。
Very Similar to Bryan Ross's, just creating the div in a more efficient manner. It may not be as straight forward, but I believe it is more performant.