第一个词选择器

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

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

替换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('' + first + '
'); };

工作演示: 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('' + first + '
'); };

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

这应该工作:

 $('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($("").html(word).addClass("em")); }); 

的jsfiddle

基本上你可以这样做

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

现在我已经回答了这个问题,但我对jquery很新,并且认为我会试一试。 请评论!

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

这可能对你有所帮助

带有jquery的String中的第一个单词

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

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

 $.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('' + first + ''); }); }; 

http://jsfiddle.net/rxAMF/

 /* 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 ? " " + last + "" : last)); }; $.fn.firstWord = function() { var text = this.text().trim().split(" "); var first = text.shift(); this.html((text.length > 0 ? ""+ first + " " : first) + text.join(" ")); }; $("#firstWord").firstWord(); $("#lastWord").lastWord();