2013-03-21 42 views
-1
<div class="head-text"> 
    <div class="body-text"> 
     <div class="line1"> 
      This is line one1 
     </div> 
     <div class="line2"> 
      This is line one1 
     </div> 
    </div> 

    <div class="body-text"> 
     <div class="line1"> 
      This is line one2 
     </div> 
     <div class="line2"> 
      This is line one2 
     </div> 
    </div> 

    <div class="body-text"> 
     <div class="line1"> 
      This is line one3 
     </div> 
     <div class="line2"> 
      This is line one3 
     </div> 
    </div> 
</div> 

问题是我想单独检索文本。我试过使用循环,但我要么得到整个事情,要么只是第一件事。

例如:如果我需要在循环中检索文本“This is line one2”,那么我应该怎么做?

回答

0
$('body-text').each(function() { 
    $(this).children('div').each(function() { 
     myText = $(this).text(); 
    } 
} 

更新:它听起来不像你想根据你的意见一个循环。你可能只是想,例如:

$('.body-text:nth-child(3)').children('.line2').text(); 
+0

这将不会工作。选择不正确..,')'失踪.. – Anujith 2013-03-21 20:32:41

+0

感谢。我也错过了一个小点。累了的眼睛。 :-) – isherwood 2013-03-21 20:33:56

+0

不,这实际上不起作用。我一次又一次地获得价值。我的必要性是当我点击

This is line one3
我需要一个输出显示“This is line one3” 谢谢。 – 2013-03-21 20:34:02

0

使用

$("div[class^=line]").each(function(){ 
    alert($(this).text()); 
}); 

如果你需要所有的人都在一个数组:

var arr = $("div[class^=line]").map(function(){ 
      return $(this).text(); 
      }).get(); 

如果您需要点击警报:http://jsfiddle.net/mzZR8/

$("div[class^=line]").click(function(){ 
    alert($(this).text()); 
}); 
+0

不是一个坏方法。我可能会将.body-text作为父选择器放在那里,以确保您不会在页面上选取其他类似的类。 – isherwood 2013-03-21 20:30:34

+0

我想显示div的“body-text”的onclick。我的意思是在点击整个“body-text”div时,我需要将文本显示为“This is line one3”或“This is line one1”等 谢谢。 – 2013-03-21 20:47:48

+0

听起来好像您要求函数在单击父项时随意返回两个子元素的文本之一。这是行不通的。 – isherwood 2013-03-21 21:18:39

0

试试 这个!

$(".body-text").click(function(evt){ 
    alert($(evt.target).text()); 
}); 

的“EVT”的说法,您可以访问“目标”,这是什么,你直接点击。

继承人fiddle