2010-07-23 5 views
4

jQuery에 대해 배우기 시작했으며 jQuery를 사용하여 셀렉터를 사용하여 특정 ID와 클래스를 검색하는 방법에 익숙해졌습니다. 단락 안의 평범한 오래된 텍스트의 문자열을 식별하는 것도 가능합니까? 예를 들어jQuery를 사용하여 HTML 내에서 문자열을 찾을 수 있습니까?

, 나는이 단락 태그 내에서 "휘발유"를 찾아 링크로 변환 싶어 말 : 당신은 정말 할 jQuery를 사용하지 것이다

<p>His veins burned gasoline. 
    It kept his motor running but it never kept him clean.</p> 

답변

4

바꾸기. 대신 자바 스크립트의 .replace() 메소드를 사용하십시오.

(I 단락에게 올바른 단락을 지정하는 ID를 주었다.)

그것을 밖으로 시도 :http://jsfiddle.net/yRCjN/1/

HTML

<p id='myparagraph'>His veins burned gasoline. 
    It kept his motor running but it never kept him clean.</p> 

자바 스크립트/

 // Cache the selected element so it only runs once. 
var $paragraph = $('#myparagraph'); 

    // Get the text and update it with the <a> tag 
var newcontent = $paragraph.text().replace(/(gasoline)/,'<a href="/some/link/path">$1</a>'); 

    // Set the new content 
$paragraph.html(newcontent); 
jQuery를
  • 당신은
  • 사용 jQuery의 .html() 방법은 새와 단락을 업데이트 jQuery의 .text()

  • <a> 요소에 싸여 같은 텍스트 "가솔린"대체 텍스트 내용에 .replace()를 수행하여 단락의 콘텐츠를 함유량.

  • http://api.jquery.com/text/

  • http://api.jquery.com/html/

파크 애비뉴가 리드 ...

+0

대단히 감사합니다! 이것으로 충분히 작업 할 수 있습니다. JSfiddle에 나를 초대해 주셔서 감사합니다. –

1
var text = jQuery("#someId").text(); 
text = textreplace(/(gasoline)/, "<a href='http://some.url.here'>$1</a>"); 
jQuery("#someId").html(text); 
+0

선택기에서 "P"에 대한 필요가 없습니다; 'jQuery ('# someId')' – Matt

+0

@Matt. 참된. 편집 중! –

1
$('p').text().replace('gasoline', '<a href="#">gasoline</a>'); 
관련 문제