Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

javascript - Get value from <td> where <th> matches text

With a system that I use you can create custom fields. These fields all have the same html and css. Now I would like to get the value td where the th is week.

Now I use:

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

Which works but then I have to make sure it always is the last field. Is there a better way of doing this?

   <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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Var 1:

var week=0;
$('table tr td').each(function(){
	if($(this).prev().text()=='Week'){
		week=parseInt($(this).text(), 10);
	}
});
console.log(week);
<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...