0

我需要做的是抓住<p>元素中的第一个标签,遍历所有单词,然后将它们包装在<span>标签中。<p>我为此编写了一个脚本,我认为该脚本有效,但是当标签中包含某些字符时,它似乎会中断。我不知道是哪个字符导致它中断。

这是我当前的代码:

$(document).ready(function(){
// Transform is set on html tag by modernizr
// Apply this on all .quote boxes, even if there are multiple (most likely aren't)
$('.csstransforms .quote').each(function() {
    // Get data
    var elem = $(this).find('p:first'),
        html = elem.text(),
        words = html.split(" "),
        charCount = html.length

    $(this).append('<p class="fixed"></p>');

    // Add new words
    var tmpWord = '';
    for(i=0; i< words.length ; i++) {
        tmpWord = $.trim(words[i]);

        if(tmpWord && tmpWord != "") {
            // Maybe replace with $(elem).next('.fixed') or something?
            $('.csstransforms .quote .fixed').append('<span>'+ tmpWord +' </span>');   
        }
    }

    // Check word count, make size smaller if needed
    if(charCount > 150) {
        // Add class to .quote box
        $(this).addClass('smaller');
    }

    // Hide original <p>
    $(elem).hide();
});
});

我得到的错误如下,您在文本中看到的是实际报价:

Uncaught Error: Syntax error, unrecognized expression: "In the decade or so, science has discovered a tremendous amount about the role emotions play in our lives. Researchers have found that even more than IQ, your emotional awareness and abilities to handle feelings, will determine your success and happiness in all  walks of life, including family relationships". – John Gottman, Ph. D. 

关于导致此问题的原因以及如何解决的任何想法?一直在咀嚼它一段时间没有成功。

更新: Jsfiddle 显示相同的错误:http: //jsfiddle.net/Uugbc/

4

1 回答 1

3

只是为了澄清。你的小提琴有 charCount = $(html).text().length; ,但你的变量html不是 jQuery 对象。

这会更好

    var elem = $(this).find('p:first'),
        html = elem.text(),
        words = html.split(" "),
        charCount = html.length; // here you had $(html).text().length;
于 2012-10-19T14:01:06.633 回答