使用jquery解析html和文本之间的比较

时间:2013-07-26 07:22:13

标签: jquery

我只是想知道是否可以比较解析html和普通文本?

我将简要解释一下我的问题:

我有一个场景,我必须将h.

中的no.of字符计为'10'
eg: <p style="font-family:verdana">What is the advantage of jquery</p>

如果算上这个html,我就不能使用文本的确切字符,我只需要10个字符,我必须将剩下的字符分别显示为两个变量,如下所示,我不应该丢失第二个变量中的段落样式。

eg: var one = "What is th";
    var two = "<p style="font-family:verdana">e advantage of jquery</p>";

如果我使用.parse(),我可以用它与普通文本进行比较,我不知道确切的答案如何继续,如果有人有想法,你能建议我如何做示例代码吗? / p>

或者是否有可能显示如下:

eg: var one = "<p style="font-family:verdana">What is th</p>";
    var two = "<p style="font-family:verdana">e advantage of jquery</p>";

先谢谢。

3 个答案:

答案 0 :(得分:0)

尝试

var html = '<p style="font-family:verdana">What is the advantage of jquery</p>';
var text = jQuery(html).text();
var one = '<p style="font-family:verdana">' + text.substring(0, 10) + '</p>';
var two = '<p style="font-family:verdana">' + text.substring(10) + '</p>';

答案 1 :(得分:0)

var html = '<p style="font-family:verdana">What is the advantage of jquery</p>';

// convert HTML string to two jQuery objects
var one = $( html ), two = $( html );

// replace the text inside first object with its substring (10 characters starting at 0)
one.text( one.text().substr(0, 10) );

// replace the text inside second object with its substring (the resto of characters starting at 10)
two.text( two.text().substr(10) );

// now you have two jQuery objects, each containing a paragraph with a fragment of text.
console.log( one );
console.log( two );

答案 2 :(得分:0)

检查Fiddle

$(document).ready(function () {
    var max = 10;    
    var text = $('#elem').text();

    if(text.length > max){
        var one = text.substring(0, max);
        var short = text.substring(max);
        var clone = $('#elem').clone();
        clone.text(short);

        var temp = $('<div />');
        $(temp).append(clone);

        var two = $(temp).html();
        alert(one);
        alert(two);
    }
});