使用jQuery动态创建div

19

我正在尝试为一个动态生成的div添加背景图片。当我添加背景的CSS属性,就像下面这样时,它会破坏我的插件。

$("<div>", {
    'class': "iviewer_image_mask",
    css: "background: url('http://somesite.com/path/to/image.jpg');"
}).appendTo(this.container);

有谁知道我添加背景图片时做错了什么吗?


为什么'class'要加引号,而css不需要? - kevin628
2
background 中的那个分号正在破坏你的代码。 - kei
2
根据jQuery文档:由于class是JavaScript保留字,因此在映射中必须将其名称引用起来。http://api.jquery.com/jQuery/#jQuery2 - thindery
5个回答

27

当然你可以只使用字符串添加它,但我更喜欢这种方式,因为它更易读和干净。

$("<div>", {
    'class': "iviewer_image_mask",
    css: {
        "background": "url('http://somesite.com/path/to/image.jpg')"
    }
}).appendTo(this.container);

演示


23
根据这个SO问题中报道的一些基准测试,我认为使用jQuery创建HTML元素最有效的方法是这样的:
$('<div class="iviewer_image_mask" style="background: url(http://somesite.com/path/to/image.jpg);"></div>').appendTo(this.container);

或者为了更好的可读性:

var elm = '<div class="iviewer_image_mask" ' +
          'style="background: url(http://somesite.com/path/to/image.jpg);">'+
          '</div>';
$(elm).appendTo(this.container);

9
$("<div>")
    .addClass('iviewer_image_mask')
    .css('background', "url('http://somesite.com/path/to/image.jpg')")
    .appendTo(this.container);

9
$("<div>").attr({
    'class': "iviewer_image_mask",
    'style': "background: url('http://somesite.com/path/to/image.jpg');"
}).appendTo("body");

如果你真的需要通过属性来添加它。

0

我在这本书Beginning JavaScript and CSS Development with jQuery中读到:

在之前的章节中,你已经看到了jQuery使用的addClass()、hasClass()和removeClass()方法的示例,用于操作类名。在客户端Web开发中,被认为是最佳实践的是避免直接在JavaScript代码中放置样式声明,而是通过将样式放置在CSS中并操作元素的类名保持行为和表现的分离。这是因为它是最佳实践:它是最合理的。由于所有的表现都被整齐地包含在CSS中,行为在JavaScript中,结构在HTML中,因此你的文档变得更容易管理,因为更容易预测在哪里进行修改。如果你的样式散布在HTML中的内联样式、JavaScript中和实际样式表中,那么修改文档的表现就会变得更加困难。

所以,为了你的目的,请使用类名。像这样:

$('<div class="iviewer_image_mask background-image"></div>').appendTo(this.container);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接