第一个单词选择器

发布于 2024-10-27 10:23:33 字数 95 浏览 2 评论 0原文

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

笨死的猪 2024-11-03 10:23:33

替换 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/

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/

抚笙 2024-11-03 10:23:33

这应该有效:

$('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

This should work:

$('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

套路撩心 2024-11-03 10:23:33

现在我已经回答了这个问题,但我对 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);
});

Now I now this has already been answered, but I am very new to jquery and thought I would give it a go. Comments please!

$('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);
});
南渊 2024-11-03 10:23:33

基本上你可以这样做

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

basicly you can do like this

$('ELEMENT_SELECTOR').text().split(' ')[0]
自由范儿 2024-11-03 10:23:33

这可能会帮助你

jquery 字符串中的第一个单词

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

This may help you

First Word in String with jquery

$('div.message').text(function(i,txt) {
    var name = $('div.name').text().split(' ')[ 0 ];   
});
未蓝澄海的烟 2024-11-03 10:23:33

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

$.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/

Actually, if you want to use it as a plugin, so that it would do it for all the items in the selector, not only the first one, use this one:

$.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/

念三年u 2024-11-03 10:23:33
/*
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();
/*
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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文