2

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

我将简要解释我的问题:

我有一个场景,我必须从 html 中将字符数计算为“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(),我可以用来与普通文本进行比较,我不知道确切的答案如何进行,如果有人有想法,你能通过给出示例代码来建议我怎么做吗?

或者有没有可能显示如下:

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

提前致谢。

4

3 回答 3

0

检查小提琴

$(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);
    }
});    
于 2013-07-26T07:39:20.853 回答
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>';
于 2013-07-26T07:38:32.130 回答
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 );
于 2013-07-26T07:38:48.960 回答