Html标签不在工具提示中呈现

时间:2013-07-26 13:56:15

标签: jquery html css

我正在使用.html()获取span tag的内容并将其显示为工具提示,但span标记内的html标记直接显示在工具提示中,而不进行渲染。

<div>
<a href="#">Parent
<span>
<strong>It is a long established</strong> The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to usi<em>ng 'Content here, content here', m</em>aking it look like readable English. Many desktop publishing packages
</span>
</a>
</div>

的JavaScript

$(this).hover(function(){
        // Hover over code

        var title = $(this).find('span').html();

        if(title){
        $('<p class="tooltip"></p>')
        .text(title)
        .appendTo('body')
        .fadeIn('slow');
    }
}, function() {
        // Hover out code

        $('.tooltip').remove();
}).mousemove(function(e) {
        var mousex = e.pageX + 20; //Get X coordinates
        var mousey = e.pageY + 10; //Get Y coordinates
        $('.tooltip')
        .css({ top: mousey, left: mousex })
});

小提琴:http://jsfiddle.net/qA88d/

5 个答案:

答案 0 :(得分:5)

您正在使用text()。在这里查看工作演示:http://jsfiddle.net/qA88d/1/

变化:

.text(title)

.html(title)

答案 1 :(得分:4)

使用.html()代替.text()

$(this).hover(function(){
    // Hover over code

    var title = $(this).find('span').html();

    if(title){
    $('<p class="tooltip"></p>')
    .html(title)  // Change here
    .appendTo('body')
    .fadeIn('slow');
  }
  }, function() {
    // Hover out code

    $('.tooltip').remove();
  }).mousemove(function(e) {
    var mousex = e.pageX + 20; //Get X coordinates
    var mousey = e.pageY + 10; //Get Y coordinates
    $('.tooltip')
        .css({ top: mousey, left: mousex })
   });

这是一个工作小提琴:http://jsfiddle.net/qA88d/2/

答案 2 :(得分:3)

您获取了跨度的html,但随后将其设置为工具提示作为文本。您还需要将其设置为html:

var title = $(this).find('span').html();

if (title) {
    $('<p class="tooltip"></p>')
        .html(title) // <--- right here
        .appendTo('body')
        .fadeIn('slow');
}

答案 3 :(得分:3)

将您的JS从.text()更改为.html()

<强> View the JSFiddle

$(this).hover(function(){
        // Hover over code

        var title = $(this).find('span').html();

        if(title){
        $('<p class="tooltip"></p>')
        // Change the line below!
        .text(title) // CHANGE THIS TO `.html(title)`
        // ^ Should be .html() [So it parses and renders the HTML]
        .appendTo('body')
        .fadeIn('slow');
    }
}, function() {
        // Hover out code

        $('.tooltip').remove();
}).mousemove(function(e) {
        var mousex = e.pageX + 20; //Get X coordinates
        var mousey = e.pageY + 10; //Get Y coordinates
        $('.tooltip')
        .css({ top: mousey, left: mousex })
});

答案 4 :(得分:1)

尝试这样

$(this).hover(function(){
    // Hover over code

    var title = $(this).find('span').html();

    if(title){
    $('<p class="tooltip"></p>')
    .html(title)
    .appendTo('body')
    .fadeIn('slow');
}}