如何選擇具有特定文本的框?

[英]How can I select a box which has specific text?


I have this HTML:

我有這個HTML:

<h5>something</h5>
<ul>
   <li class="name">John</li>
   <li class="age">21</li>
</ul>
<h5>specific text</h5>
<ul>
   <li class="name">Peter</li>
   <li class="age">19</li>
</ul>
<h5>something else</h5>
<ul>
   <li class="name">Ali</li>
   <li class="age">62</li>
</ul>

I want to select this part:

我想選擇這一部分:

<h5>specific text</h5>
<ul>
   <li class="name">Peter</li>
   <li class="age">19</li>
</ul>

The logic is the content of <h5> tag. I want the one which is specific text. Actually expected result is an array of both that name and that age. Some thing like this: var res = ['Peter', 19];.

邏輯是

標簽的內容。我想要一個具體的文本。實際上,預期結果是一個名字和年齡的數組。類似這樣的東西:var res = ['Peter', 19];

But my code selects all those <ul>s:

但是我的代碼選擇了所有的

    s:

$('ul').map(function (){
   var res = [$(this).find('li.name').text(), $(this).find('li.age').text()];
});

How can I fix it?

我怎樣才能修好它呢?

2 个解决方案

#1


7  

You can use :contains() to find the H5 that contains the specific string you want. Then use .next() to get that ul associated with the h5

可以使用:contains()查找包含所需特定字符串的H5。然后使用.next()來獲得與h5相關的ul。

$("h5:contains('specific text')").next('ul').map(function (){
   var res = [$(this).find('li.name').text(), $(this).find('li.age').text()];
   console.log(res)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h5>something</h5>
<ul>
   <li class="name">John</li>
   <li class="age">21</li>
</ul>
<h5>specific text</h5>
<ul>
   <li class="name">Peter</li>
   <li class="age">19</li>
</ul>
<h5>something else</h5>
<ul>
   <li class="name">Ali</li>
   <li class="age">62</li>
</ul>

#2


0  

Jquery script for getting data from ul list :

從ul列表獲取數據的Jquery腳本:

$('ul').map(function (){
   var res = [$(this).find('li.name').text(), $(this).find('li.age').text()];
  // console.log(res);
   
});
var htmVal = '';
$('h5').each(function(index){
htmVal = $(this).html();
if(htmVal == 'something else'){
var detail ={name:$(this).next().find('li.name').html(),age:$(this).next().find('li.age').html()};
console.log(detail);
}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h5>something</h5>
<ul>
   <li class="name">John</li>
   <li class="age">21</li>
</ul>
<h5>specific text</h5>
<ul>
   <li class="name">Peter</li>
   <li class="age">19</li>
</ul>
<h5>something else</h5>
<ul>
   <li class="name">Ali</li>
   <li class="age">62</li>
</ul>


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/05/08/7128f9d86318a59425fa7990ec436f7f.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com