0

当我输入以下代码时:

$('.whatever').html("LOL");

有用。但是在我正在构建的网站中,我需要添加的不仅仅是一个字符串。

这是我想补充的:

<div class="pic"><img class="left" src="img/happy-man.jpg"/ ></div>
<div class="pic"><img class="happy" src="img/happy-woman.jpg"/ ></div>
<div class="pic"><img class="right" src="img/happy-celeb.jpg"/ ></div>

但是当我将上面的 HTML 代码放入 html() 函数时,什么也没有发生。我想知道我在语法方面犯了什么明显的错误。欣赏它!

4

5 回答 5

1

尝试使用单引号$('.whatever').html('LOL');

http://jsfiddle.net/83DSu/1/

于 2012-12-11T14:00:30.940 回答
1
$('.whatever').html('<div class="pic"><img class="left" src="img/happy-man.jpg"/ ></div><div class="pic"><img class="happy" src="img/happy-woman.jpg"/ ></div><div class="pic"><img class="right" src="img/happy-celeb.jpg"/ ></div>')

以下代码将允许您替换 div 的 html 内容

或者你只是做一个字符串

text= '<div class="pic"><img class="left" src="img/happy-man.jpg"/ ></div>'+'<div class="pic"><img class="happy" src="img/happy-woman.jpg"/ ></div>'
$('.whatever').html(text)
于 2012-12-11T14:52:35.723 回答
0

如果您正确逃脱,它可以完美运行

具有三个不同选项的演示

var html1 ="<div class=\"pic\"><img class=\"left\" src=\"img/happy-man.jpg\"/ >" + 
           "</div><div class=\"pic\"><img class=\"happy\" src=\"img/happy-woman.jpg\"/ ></div>" +
           "<div class=\"pic\"><img class=\"right\" src=\"img/happy-celeb.jpg\"/ ></div>";

$('#whatever').html(html1);

var html2 = "<div class='pic'><img class='left' src='img/happy-man.jpg'/ ></div>" + 
            "<div class='pic'><img class='happy' src='img/happy-woman.jpg'/ ></div>" + 
            "<div class='pic'><img class='right' src='img/happy-celeb.jpg'/ ></div>";

$('#whatever2').html(html2);

var html3 = '<div class="pic"><img class="left" src="img/happy-man.jpg"/ ></div>' +
            '<div class="pic"><img class="happy" src="img/happy-woman.jpg"/ ></div>' +
            '<div class="pic"><img class="right" src="img/happy-celeb.jpg"/ ></div>';

$('#whatever3').html(html3);
于 2012-12-11T14:29:04.320 回答
0

单引号和双引号可能有问题

$('.whatever').html(
   '<div class="pic"><img class="left" src="img/happy-man.jpg"/ ></div>'+
   '<div class="pic"><img class="happy" src="img/happy-woman.jpg"/ ></div>'+
   '<div class="pic"><img class="right" src="img/happy-celeb.jpg"/ ></div>'
);

http://jsfiddle.net/83DSu/

于 2012-12-11T14:37:07.927 回答
0

另一种方法是:

var imgList = [
        ["img/happy-man.jpg","left"]
        ,["img/happy-woman.jpg","happy"]
        ,["img/happy-celeb.jpg","right"]
    ], cur=0,
    whatever = $('#whatever');
    whatever.html("");

$.each(imgList,function(){
    console.log(imgList[cur][1]);
    whatever
        .append( $("<div />")
                .addClass("pic")
                .html( $("<img />")
                      .addClass(imgList[cur][1])
                      .attr("src",imgList[cur][0])
                    )
              );
        cur++;
});​

它看起来更复杂,但它可以让您更快地控制 HTML 并将所有链接放在一个位置。

http://jsfiddle.net/daCrosby/Fwwd3/

于 2012-12-11T14:47:57.617 回答