【问题标题】:First word selector第一个词选择器
【发布时间】:2011-07-24 10:28:13
【问题描述】:

如何选择 div 中的第一个单词?

我需要能够在第一个单词之后插入换行符,或者将其包装在 span 标签中。我需要为同一类的页面上的多个 div 执行此操作。

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    替换 HTML 将导致事件处理程序未绑定,替换元素的整个文本将导致 HTML 标记丢失。最好的方法是保持任何 HTML 不变,只操作匹配元素的第一个文本节点。要获取该文本节点,您可以使用.contents().filter()

    function wrapFirstWord () { 
        // Select only the first text node
        var node = $("div").contents().filter(function () { 
                return this.nodeType == 3;
            }).first(),
    
        // Get the text... 
            text = node.text(),
    
        // ... and the first word
            first = text.slice(0, text.indexOf(" "));
    
        if (!node.length)
            return;
    
        // Remove the first word from the text
        node[0].nodeValue = text.slice(first.length);
    
        // Add it back in with HTML around it
        node.before('<span>' + first + '</span><br/>');
    };
    

    工作演示:http://jsfiddle.net/9AXvN/

    使用此方法将确保操作第一个单词不会对元素的其余内容产生不必要的副作用。


    您可以轻松地将其作为 jQuery 的扩展,并为要换行的单词数量提供可选值:

    $.fn.wrapStart = function (numWords) { 
        var node = this.contents().filter(function () { 
                return this.nodeType == 3 
            }).first(),
            text = node.text(),
            first = text.split(" ", numWords).join(" ");
    
        if (!node.length)
            return;
    
        node[0].nodeValue = text.slice(first.length);
        node.before('<span>' + first + '</span><br/>');
    };
    

    工作演示:http://jsfiddle.net/9AXvN/1/

    【讨论】:

    • +1 人 我迟到了 1 分钟!只是做了同样的事情。 jsfiddle.net/markcoleman/NdhSj
    • 谢谢@Andy E,我不确定我是不是很慢,但是我如何指定包装了多少个单词?
    • @jdln,可以在 wrapStart() 调用中指定字数。 $("div").wrapStart(2);。另外,你应该接受这个答案而不是我的,因为这绝对是一个更好的方法:)
    • @AndyE node[0].nodeValue 是什么意思?新手试图理解代码... node[0] 是否与 text 匹配,nodeValue 是否与 slice() 匹配?如果是这样,您是如何定义 nodeValue 的?
    • @ShaltNot: node 是 jQuery 包装的对象,所以 node[0] 指的是我使用 jQuery 选择的底层 DOM 文本节点。它在功能上等同于node.get(0)nodeValue 是所有文本节点上的属性,它是访问文本节点文本的跨浏览器兼容方法。
    【解决方案2】:

    这应该可行:

    $('div.message').each(function() {
       var html = $(this).html();
       var word = html.substr(0, html.indexOf(" "));
       var rest = html.substr(html.indexOf(" "));
       $(this).html(rest).prepend($("<span/>").html(word).addClass("em"));
    });
    

    JSFiddle

    【讨论】:

      【解决方案3】:

      现在我已经回答了这个问题,但我对 jquery 很陌生,我想我会试一试。欢迎评论!

      $('div.message').each(function(index) {
          //get the first word
          var firstWord = $(this).text().split(' ')[0];
      
          //wrap it with span
          var replaceWord = "<span class='myClass'>" + firstWord + "</span>";
      
          //create new string with span included
          var newString = $(this).html().replace(firstWord, replaceWord);
      
          //apply to the divs
          $(this).html(newString);
      });
      

      【讨论】:

      • 我要补充的唯一评论是,操纵$(this).html() 会导致不必要的副作用,因为它会导致内容被删除并替换为一组新元素。这意味着绑定到这些元素的任何数据或事件都将消失。这就是为什么我建议只在我的答案中更改文本节点,但似乎这不是 OP 关心的问题。
      • 谢谢。我假设我们只处理纯文本 div。
      【解决方案4】:

      基本上你可以这样做

      $('ELEMENT_SELECTOR').text().split(' ')[0]

      【讨论】:

        【解决方案5】:

        这可能对你有帮助

        First Word in String with jquery

        $('div.message').text(function(i,txt) {
            var name = $('div.name').text().split(' ')[ 0 ];   
        });
        

        【讨论】:

        • 如果div 元素中有其他HTML,这将中断。
        • @jdln 所以你只有 div 元素和文本或 div 和其他 html 元素?根据@Andy E 评论
        • 我可以控制 html 输出,所以我可以在文本周围放置一个 div。谢谢
        • 这对我不起作用,但也许我用错了。 'message' 是容器 div 和 'name' 创建的新 div 吗?
        【解决方案6】:

        实际上,如果您想将其用作插件,那么它将对选择器中的所有项目都执行此操作,而不仅仅是第一个,请使用这个:

        $.fn.wrapStart = function(numWords){
            return this.each(function(){
                $this = $(this);
                var node = $this.contents().filter(function(){
                    return this.nodeType == 3
                }).first(),
                text = node.text(),
                first = text.split(" ", numWords).join(" ");
                if (!node.length) return;
                node[0].nodeValue = text.slice(first.length);
                node.before('<span>' + first + '</span>');
            });
        };
        

        http://jsfiddle.net/rxAMF/

        【讨论】:

          【解决方案7】:
          /*
          URL → https://github.com/melbon/jquery.useWord
          */
          $.fn.lastWord = function() {
            var text = this.text().trim().split(" ");
            var last = text.pop();
            this.html(text.join(" ") + (text.length > 0 ? " <span class='lastWord'>" + last + "</span>" : last));
          };
          
          
          $.fn.firstWord = function() {
            var text = this.text().trim().split(" ");
            var first = text.shift();
            this.html((text.length > 0 ? "<span class='firstWord'>"+ first + "</span> " : first) + text.join(" "));
          };
          
          
          $("#firstWord").firstWord();
          $("#lastWord").lastWord();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-10-15
            • 1970-01-01
            • 2019-03-13
            • 1970-01-01
            • 1970-01-01
            • 2011-07-29
            • 1970-01-01
            • 2023-03-15
            相关资源
            最近更新 更多