我的.html()语法出了什么问题?

时间:2012-12-11 13:50:43

标签: javascript jquery html escaping

当我输入以下代码时:

  

$( '不管。')的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()函数中时没有任何反应。我想知道我在语法方面做了哪些明显的错误。欣赏它!

5 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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)

答案 2 :(得分:0)

如果你正确逃脱,它可以很好地工作

Demo有三个不同的选项

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);

答案 3 :(得分: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/

答案 4 :(得分: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/