从匹配文本的位置获取值

时间:2018-06-04 11:27:09

标签: javascript jquery html

使用我使用的系统,您可以创建自定义字段。这些字段都具有相同的html和css。现在我想得到值为td的数值。

现在我用:

   var week = $(this).find('td.bug-custom-field:last').text();

哪个有效,但我必须确保它始终是最后一个字段。有没有更好的方法呢?

   <table>
   <tr>
   <th class="bug-custom-field category">Name</th>
   <td class="bug-custom-field" colspan="5">Test</td>
   </tr>

   <tr>
   <th class="bug-custom-field category">Week</th>
   <td class="bug-custom-field" colspan="5">23</td>
   </tr>
   </table>

2 个答案:

答案 0 :(得分:0)

您已经拥有了所需的大部分细节。获得th之后,最强大的解决方案是前往该行,然后使用find查找td。替代方案是简单的.next(),但如果布局发生变化,则更容易中断。

var th = $("th.bug-custom-field.category:contains('Week')")
var row = $(th).closest("tr");
var week = $(row).find('td.bug-custom-field:last').text();

&#13;
&#13;
var weekTH = $("th.bug-custom-field.category:contains('Week')")
var weekTR = $(weekTH).closest("tr");
var weekTD = $(weekTR).find('td.bug-custom-field:last');
var week = $(weekTD).text();
console.log(week);
&#13;
th { text-align:left; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th class="bug-custom-field category">Name</th>
    <td class="bug-custom-field" colspan="5">Test</td>
  </tr>

  <tr>
    <th class="bug-custom-field category">Week</th>
    <td class="bug-custom-field" colspan="5">23</td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Var 1:

&#13;
&#13;
var week=0;
$('table tr td').each(function(){
	if($(this).prev().text()=='Week'){
		week=parseInt($(this).text(), 10);
	}
});
console.log(week);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<table>
   <tr>
     <th class="bug-custom-field category">Name</th>
     <td class="bug-custom-field" colspan="5">Test</td>
   </tr>

   <tr>
     <th class="bug-custom-field category">Week</th>
     <td class="bug-custom-field" colspan="5">23</td>
   </tr>
</table>
&#13;
&#13;
&#13;

Var 2:

&#13;
&#13;
var week = $('table').find('td.bug-custom-field:last').text();
console.log(week);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
   <tr>
    <th class="bug-custom-field category">Name</th>
    <td class="bug-custom-field" colspan="5">Test</td>
   </tr>

   <tr>
    <th class="bug-custom-field category">Week</th>
    <td class="bug-custom-field" colspan="5">23</td>
   </tr>
</table>
&#13;
&#13;
&#13;