【问题标题】:Creating multiple html elements using an object and jQuery使用对象和 jQuery 创建多个 html 元素
【发布时间】:2017-07-15 17:31:36
【问题描述】:

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

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

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 所写的内容是错误的,但我似乎找不到任何关于有人做类似事情的文档,所以我可能只是在处理这个错误。如果有人对不同的方法有任何建议,我绝对愿意接受。

谢谢!

【问题讨论】:

  • 你有小提琴或演示吗?
  • 这应该可以。一旦它被添加到 DOM 中,您就可以像现在一样查询它。你测试了吗?它不工作吗?

标签: javascript jquery html object


【解决方案1】:

jQuery(html, attributes) 处将prepend 设置为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()?

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 2013-03-19
      相关资源
      最近更新 更多