Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用对象和jQuery创建多个html元素_Javascript_Jquery_Html_Object - Fatal编程技术网

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

Javascript 使用对象和jQuery创建多个html元素,javascript,jquery,html,object,Javascript,Jquery,Html,Object,所以我想创建一个元素块,从对象中获取类和属性 我使用一个函数来创建对象 function profile(name, img, health, strength) { return { name: name, img: img } }; 然后我使用jQuery创建一个div,并使用该对象提供一个类 function pushProfile(profile) { $('<div />', { "class": p

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

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

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设置为jQueryhtml、attributes的属性


另请参见

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

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

你有提琴或演示吗?这应该有用。一旦它被添加到DOM中,您就可以像现在一样查询它。你测试过了吗?它不起作用吗?
function pushProfile(profile) {
    $('<div />', {
        "class": profile.name + ' profile',
        text: 'test',
        prepend: '<img src="' + profile.img + '">',
        appendTo: '.profile-class'
    });
}