jquery html()和append()不起作用

时间:2012-09-25 12:30:31

标签: javascript jquery html

由于某种原因,两种方法的结果都是TextNode。这意味着浏览器不会解析附加字符串的内容。

例如

var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").append(code);
页面上的

我有内容

"<div><p>Some</p> news are <span>here</span></div>"

这个

$("#news_details").contents() 

显示带有html源的字符串被附加(由于某些原因我不知道)作为单个textnode

但如果要输入萤火虫

var text = $('#news_detaisl').text()
$('#news_details').contents().remove()
$('#news_details').append(text)

之后,它会被解析并以正确的方式显示。

2 个答案:

答案 0 :(得分:1)

由于你没有直接提出问题,我只能假设你想要的东西。试试这个并告诉我它是否有帮助,如果它是你想要的:

var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").append($(code));

哦和$()。append和$()。html的行为方式不一样。 $()。append将输入添加为新子项,而$()。html返回元素的innerHTML或设置它。取决于您是否设置参数。

答案 1 :(得分:0)

只有这段代码工作正常,但这种奇怪的行为

var content = news.newsDetails(here async ajax request which load html snippet with content);  //content is a string with html snippet from server

$("#news_content").append(content);
var value = $(".news_title").text();
$(".news_title").contents().remove();
$(".news_title").append(value);
$(".news_details").css('display','block')

和html代码段

<div class="news_details">
    <img class="pointer" src="/static/img/close6.png" alt="close" width='16' height='16'>
    <div class="news_head gradient">
        <span>{{ item.pub_date|date:"d M Y"  }}</span>{{ item.title }}
    </div>
    <div class="clear"></div>
<div class="news_title">{{ item.full_text }}</div>