2013-04-11 3 views
0

이미 문자열 안에있는 문자열 안에 변수를 넣으려고하면 약간의 문제가 발생합니다. 기본적으로 색상 변수 (문자열, 예 : "# FF0")를 사용하여 특정 단어의 색상을 변경하려고합니다. 나는 그 변수 '<span style="color:red;">'에서 "레드"를 대체 할문자열 내부의 문자열 내부의 변수

$('#textWithTheWord').replaceWith($('<div></div>').append($('#textWithTheWord').clone()).html().replace(word, '<span style="color:red;">' + word + '</span>')); 

주 : 즉 어떤 기능을 대체하는 모양입니다. 미리 감사드립니다. 그 코드의 모든 요소에있는 텍스트의 색상을 변경 만있는 경우

+0

'# textWithTheWord'는'span'을 포함하고있는'element'이고,'color'를 설정하는'style' 속성을 가지고 있습니다. 그런 다음'span' 요소에 대한'color' 값을 수정하고 싶습니다. 그게 맞습니까? 그렇다면 문자열을 조작하여이 작업을 수행하려는 이유가 있습니까? – plalx

+0

@plalx 네, 지금까지, 당신 말이 맞아요. [링크] (http://stackoverflow.com/questions/10328281/need-to-replace-font-for-a-particular : 나는 특정 단어의 색상이 여기에 있었다 내가 찾을 수있는 유일한 솔루션을 변경하려 -워드). –

+0

귀하의 문제에 대한 답변을 게시했습니다. 도움이되기를 바랍니다. 최고의 행운! ;) – plalx

답변

2

쉬운 해결책은 요소의 innerHTML 속성을 span에있는 단어를 감싸는 새 html 문자열로 바꾸는 것입니다. 그러나 매우 유연한 솔루션이 아니기 때문에 innerHTML 속성을 바꾸면 텍스트 노드 만 포함하는 요소를 대상으로하지 않는 한 모든 요소가 갱신되고 예기치 않은 결과가 발생할 수 있습니다.

this is some text and I want to replace the word cool 

당신은 할 수 : :

var $body = $(document.body); 

$body.html($body.html().replace(/\b(cool)\b/g, '<span style="color: red;">$1</span>')); 
여기

, 모든 멋진 단어를 일치 그들에 캡처 그룹을 만들 것입니다 /\b(cool)\b/g 정규식 수

body이 텍스트가 포함되어 있다고 가정하자 우리는 대체 표현식에서 이것을 $1으로 참조 할 것입니다. data-styled-text 속성을 가진 span 내에 포함되지 않은 텍스트 노드를 통해

  • 루프 :

    그러나, 가장 진보 된 솔루션은 아마 다음과 같이 구현 될 수있다. (textNode.parentNode 속성을 확인할 수 있습니다.)

  • <span data-styled-text> 태그로 원하는 단어를 말하십시오. 살펴보기 https://developer.mozilla.org/fr/docs/DOM/Text.splitText
  • 모든 <span data-styled-text> 요소를 쿼리하고 원하는대로 조작하십시오.

그 개념의 주위에 장난 삼아하고 난 당신이 특정 텍스트를 대상으로하는 regex을 사용하여 원하는 어떤 방법으로 텍스트를 조작 할 수있는 방법을 보여줍니다 당신을 위해 바이올린을 만들 수 있습니다. 나는 당신이 페이지에 텍스트로 원하는대로 무엇이든 할 수있게 해주는 2 가지 주요 기능인 wrapTextstyleText을 만들었습니다. 그것은 더 최적화 될 수 있지만 아이디어를 얻을 것입니다.

다음 기능을 사용하면 텍스트 노드의 텍스트를 포장 할 수 있습니다 http://jsfiddle.net/scarsick/tX4Ge/1/

에서보세요.

function wrapText(textNode, textRx, wrapFn) { 
    var global = textRx.global, 
     wrapEl, 
     result, 
     rightTextNode, 
     matchedText, 
     index; 

    while (result = textRx.exec(textNode.nodeValue)) { 
     rightTextNode = textNode.splitText(index = result.index); 
     rightTextNode.nodeValue = rightTextNode.nodeValue.substring((matchedText = result[0]).length); 
     wrapEl = wrapFn(matchedText, index); 
     wrapEl.appendChild(document.createTextNode(matchedText)); 
     rightTextNode.parentNode.insertBefore(wrapEl, rightTextNode); 

     if (!global) { 
      break; 
     } 

     textNode = rightTextNode; 
     textRx.lastIndex = 0; 
    }  
} 

다음 기능을 사용하여 요소 내에 포함 된 텍스트의 스타일을 지정할 수 있습니다.

function styleText(el, textRx, styleFn) { 
    var wrapEl = document.createElement('span'), 
     slice = [].slice; 

    wrapEl.setAttribute('data-styled-text', 'true'); 

    styleText = function(el, textRx, styleFn) { 
     var childNodes = slice.call(el.childNodes, 0), 
      i = 0, 
      len = childNodes.length, 
      node; 

     for (; i < len; i++) { 
      node = childNodes[i]; 

      switch (node.nodeType) { 
       case 3: 
        if (!node.parentNode.getAttribute('data-styled-text')) { 
         wrapText(node, textRx, function (text, index) { 
          var el = wrapEl.cloneNode(); 

          styleFn(el, text, index); 

          return el; 
         }); 

         continue; 
        } 

        styleFn(node.parentNode); 
        break; 
       case 1: 
        styleText(node, textRx, styleFn); 
        break; 
      } 
     } 
    }; 

    styleText(el, textRx, styleFn); 
} 
0

, 당신과 같이 크게 그것을 단순화 할 수 있습니다 :

var color = "#ff8877"; 
$('#textWithTheWord').css('color', color); 

http://api.jquery.com/css/

에 대해 연주 할 필요가 없습니다 DOM 또는 문자열 연결을 사용하여 요소의 속성 또는 스타일을 변경합니다. jQuery에는 이미 원하는 것을 수행하는 함수가있을 것이다.

관련 문제