2011-03-28 10 views
12

div에서 첫 번째 단어를 선택하려면 어떻게해야합니까?첫 번째 단어 선택기

첫 단어 뒤에 줄 바꿈을 삽입하거나 span 태그에 줄 바꿈을 할 수 있어야합니다. 동일한 클래스의 페이지에서 여러 div에 대해이 작업을 수행해야합니다.

답변

28

HTML을 바꾸면 이벤트 핸들러가 언 바운드되고 요소의 전체 텍스트를 바꾸면 HTML 마크 업이 손실됩니다. 가장 좋은 방법은 일치하는 요소의 첫 번째 텍스트 노드 만 조작하여 HTML을 그대로 둡니다. 첫 번째 단어를 조작하는 나머지에 원치 않는 부작용이 없다는 것을 보장합니다이 방법을 사용 http://jsfiddle.net/9AXvN/

:

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

근무 데모 : 텍스트 노드를 얻으려면, 당신은 .contents().filter()을 사용할 수 있습니다 요소의 내용

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

+2

+1 남자 나는 1 분 늦었습니다! 그냥 똑같은 짓을 했어. http://jsfiddle.net/markcoleman/NdhSj/ –

+0

감사합니다. @Andy E, 메신저가 느린 지 확실하지 않지만 얼마나 많은 단어가 줄 바꿈되었는지 지정할 수 있습니까? – Evans

+3

@jdln에서 wrapStart() 호출에서 단어 수를 지정할 수 있습니다. '$ ("div"). wrapStart (2);'.또한, 내 대답 대신이 대답을 받아 들여야합니다. – Dogbert

1

이 당신에게

First Word in String with jquery basicly

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

'div'요소에 다른 HTML이 있으면 깨질 수 있습니다. –

+0

@jdln 그래서 div 요소와 text 또는 div가 다른 html 요소와 함께 있습니까? @Andy E comment에 따라 – Vicky

+0

나는 텍스트 주위에 div를 둘 수 있도록 html 출력을 제어합니다. 감사합니다 – Evans

3

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

같이 할 수있는 도움이 될 수 있습니다이 작업을해야합니다 :

$('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를 확장으로이에 압정 수 있습니다 이제 나는 이제 이미 답변을 얻었지만 나는 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); 
}); 
+0

내가 추가 할 유일한 주석은'$ (this) .html()'을 조작하면 내용이 제거되고 새로운 요소 세트로 대체되기 때문에 원하지 않는 부작용이 발생할 수 있다는 것입니다. 즉, 해당 요소에 바인딩 된 모든 데이터 또는 이벤트가 사라집니다. 이 이유는 텍스트 노드를 내 대답에만 변경하는 것이 좋습니다. 그러나 이것이 OP에 대한 우려가 아닌 것으로 보입니다. –

+0

감사. 나는 평범한 텍스트 div를 다루고 있다는 가정하에 작업을하고있었습니다. –

1

사실,뿐만 아니라 첫 번째, 사용이 하나

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

0
/* 
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();