gpt4 book ai didi

javascript - 使用对象和 jQuery 创建多个 html 元素

转载 作者:行者123 更新时间:2023-12-03 03:52:03 25 4
gpt4 key购买 nike

所以我想创建一个元素 block ,从对象中获取类和属性。

我使用函数来创建对象

function profile(name, img, health, strength) {
return {
name: name,
img: img
}
};

然后我使用 jQuery 创建一个 div 并使用该对象提供一个类

function pushProfile(profile) {
$('<div />', {
"class": profile.name,
"class": 'profile',
text: 'test'
}).appendTo('.profile-class');
};

到目前为止,一切似乎都正常。我的问题是我可以将嵌套元素添加到同一函数内的新 div 中吗?像这样的吗?

function pushProfile(profile) {
$('<div />', {
"class": profile.name,
"class": 'profile',
text: 'test'
}).appendTo('.profile-class');
$('.' + profile.name).prepend('<img src=' + '"' + profile.img + '" />');
};

我相当确定我为添加 img 所写的内容是错误的,但我似乎找不到任何关于某人做类似事情的文档,所以我可能只是在做这个错误。如果有人对不同的方法有任何建议,我绝对愿意接受。

谢谢!

最佳答案

prepend 设置为 attributes 的属性,位于 jQuery(html, attribute)

function pushProfile(profile) {
$('<div />', {
"class": `${profile.name} profile`,
text: 'test',
prepend: `<img src="${profile.img}"/>`
}).appendTo('.profile-class');
};

另请参阅How to pass options objects as parameters to method set at second parameter of jQuery()?

关于javascript - 使用对象和 jQuery 创建多个 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45120963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com