2013-08-22 2 views
0

나는이 경우 "Guns N Roses"라는 아티스트의 이름에만 액세스하려고합니다. 이미 솔루션을 가지고 있습니다 : http://jsfiddle.net/QRBgp/4/jQuery는 가장 깊은 요소 모범 사례에서 텍스트 가져 오기

그러나 이것에 대한 짧은 방법이 있습니까? 더 좋은 방법? 나는 그것이 "작동한다면, 왜 묻 느냐"라고 말할 것이지만, 나는 호기심이 많다.

는 HTML :

<div id="now_playing" class="tab ui-tabs-panel ui-widget-content ui-corner-bottom"> 
<div class="banner"> … </div> 
<div class="banner_wrap banner_top_left"></div> 
<div class="banner_wrap banner_bottom_left"></div> 
<div class="banner_wrap banner_top_right"></div> 
<div class="banner_wrap banner_bottom_right"></div> 
<div class="play-cont"> 
    <div class="curr-song-block clearfix"> 
     <div class="thumb"> … </div> 
     <div class="descr"> 
      <em> … </em> 
      <h3> … </h3> 
      <div class="data-block"> 
       <div class="data"> 
        <strong> by </strong> 
    Guns N Roses 
</div> 
       <div class="data"> 
        <strong> on </strong> 
    Appetite for Destruction 
</div> 
       </div> 
      </div><p> … </p> 
     </div> 
    </div> 
    <div id="accordion" class="ui-accordion ui-widget ui-helper-reset" role="tablist"> … </div> 
</div> 

jQuery를 내가 사용 :

$(".data-block").click(function() { 
alert($('#now_playing').find('.descr').find('.data-block').find('.data:first-child').clone().children("strong").remove().end().text()); 
}); 
+0

당신은 [jQuery를에 깊은 아이를 선택 http://codereview.stackexchange.com/ – Smeegs

+0

이를 게시 할 수 있습니다 ] (http://stackoverflow.com/questions/3787924/select-deepest-child-in-jquery) - 비슷한 문제입니다. 희망이 도움이됩니다. – ksalk

답변

1

당신은 바로 사용할 수 있습니다

당신이 비록 짧은 원하는 경우, 쉽게 경우 것
alert($('#now_playing .data:first').text().replace(/\s+by\s+/,'')); 
//or: 
alert($.trim($('#now_playing .data:first').contents()[2].textContent)); 

방금 요소를 사용했습니다. 텍스트 노드 -이 작업을 훨씬 쉽게 할 수 있습니다. 예 : $("#now_playing .artist_name").text()

+0

나는 자신이 소유하지 않은 사이트에서 파싱을하고 있기 때문에 HTML을 "리팩터링"할 수는 없습니다.) 감사합니다. 나는 당신의 접근 방식을 좋아합니다. –

1

<span />에 이름을 포함하고 클래스 이름을 지정하지 않은 이유가 궁금합니다. 그런 다음 클래스별로 선택할 수 있습니다. 이렇게하면 마크 업과 코드가 만들어집니다 : a) 더 읽기 쉽고 이해할 수 있고, b) 더 빨리 말하십시오. 단어 한 개를 지우는 데 단지 clone()을 사용할 필요가 없기 때문입니다.

HTML

<div class="data"> 
    <strong>by</strong> <span class="artist">Guns n' Roses</span> 
</div> 

jQuery를

#('#now-playing .descr .data:first-child').find('.artist').text(); 
+0

내가 소유하지 않은 사이트에서이 구문을 파싱합니다. 그 이유는 HTML을 "리팩터링"할 수 없기 때문입니다.) –

1
$(".data-block").click(function() { 
alert($(this).('.data:first-child').clone().children("strong").remove().end().text());}); 
관련 문제