第一个单词选择器 [英] First word selector

查看:94
本文介绍了第一个单词选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

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

工作演示: 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/

How can I select the first word in a div?

I need to be able to insert a line break after the first word, or wrap it in a span tag. I need to do this for multiple divs on a page with the same class.

解决方案

Replacing HTML will result in event handlers being unbound and replacing the entire text for an element will result in HTML markup being lost. The best approach leaves any HTML untouched, manipulating only the first text node of the matching element. To get that text node, you can use .contents() and .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/>');
};

Working demo: http://jsfiddle.net/9AXvN/

Using this method will ensure that manipulating the first word will have no unwanted side effects on the rest of the element's content.


You can easily tack this on as an extension to jQuery, with an optional value for the number of words you want to wrap:

$.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/>');
};

Working demo: http://jsfiddle.net/9AXvN/1/

这篇关于第一个单词选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆