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

时间:2017-07-15 17:31:37

标签: javascript jquery html object

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

我使用一个函数来创建对象

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而写的内容是错误的,但我似乎无法找到任何与此类似的人的文档,所以我可能只是错了。如果有人对不同的方法有任何建议,我绝对愿意接受。

谢谢!

2 个答案:

答案 0 :(得分:1)

prepend

attributes设为jQuery(html, attributes)的属性
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()?

答案 1 :(得分:0)

在元素构造函数的Object中设置所有属性

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