我有一个实体框架生成的表,其中包含我需要更改的td中的值.我需要逐行执行此操作,因为我需要插入一组单选按钮,但每行按钮都需要一个唯一的名称.
基本上,我需要根据id为“Rate”的td中的文本值设置一组按钮的选中值,并在从中获取值后删除现有文本.
我的表看起来像这样,
<table id="IndexTable">
<tr>
<th>CoffeeID </th>
<th>Degree </th>
<th>Weight </th>
<th>Profile </th>
<th>UsageInfo </th>
<th>Comments </th>
<th>AmbientTemp </th>
<th>rating </th>
<th>WeightDeducted </th>
<th>Selected </th>
<th>ProfileID </th>
<th>ProfileStart </th>
</tr>
<tr>
<td>1 </td>
<td>1 </td>
<td>3 </td>
<td>9 </td>
<td>Filter Brew </td>
<td>Perfecto!! </td>
<td>55 </td>
<td id="rating">4.25 </td>
<td>1 </td>
<td>4 </td>
<td>34 </td>
<td>1 </td>
</tr>
<tr>
<td>3 </td>
<td>15 </td>
<td>99 </td>
<td>87 </td>
<td>Espresso </td>
<td>WTF </td>
<td>99 </td>
<td id="rating">4.5 </td>
<td>5 </td>
<td>3 </td>
<td>66 </td>
<td>4 </td>
</tr>
我的脚本如下.
$("tr").each(function() { //get all rows in table
var str = $("text[id=rating]").val(); //assign text with matching id to str ---doesn't work
$("td").each(function() { //get all tds in current row
var newStr = ("#rating").text; //assign text in td with id rating to newStr ---- doesn't work
alert(newStr); // fires undefined for each td in table?
//This is where I want to insert radio buttons and assign the one with the value of the rating td to checked.
});
});
这只是最新的,我已经浏览了这个网站,但我看到的所有内容都没有涉及从特定行的特定列获取值,更改值以及重复每个行/列中的值.表.
我来自db背景,这非常简单,这非常令人沮丧.
解决方法
你的html有一些问题,而你的jQuery一开始就像SKS所说的那样,你的html文档中不能有多个具有相同ID的节点. ID必须是唯一的.我推荐使用一个类.
您还应该在< thead>中添加标题行和< tbody>中的表格正文
现在,在您的jQuery上,$(“td”)将找到文档中的所有td,而不仅仅是行中的td.
你会想要使用
$(this).find(‘td’)或者您可以使用.children或更高级别的选择器.有许多不同的,正确的方法来获取此信息.
我已经采用你的代码并修改它:
$("tbody").find("tr").each(function() { //get all rows in table
var ratingTdText = $(this).find('td.rating').text();
//gets the text out of the rating td for this row
alert(ratingTdText);
});
这适用于稍微修改的html:
<table id="IndexTable">
<thead>
<tr>
<th>CoffeeID </th>
<th>Degree </th>
<th>Weight </th>
<th>Profile </th>
<th>UsageInfo </th>
<th>Comments </th>
<th>AmbientTemp </th>
<th>rating </th>
<th>WeightDeducted </th>
<th>Selected </th>
<th>ProfileID </th>
<th>ProfileStart </th>
</tr>
</thead>
<tbody>
<tr>
<td>1 </td>
<td>1 </td>
<td>3 </td>
<td>9 </td>
<td>Filter Brew </td>
<td>Perfecto!! </td>
<td>55 </td>
<td class="rating">4.25 </td>
<td>1 </td>
<td>4 </td>
<td>34 </td>
<td>1 </td>
</tr>
<tr>
<td>3 </td>
<td>15 </td>
<td>99 </td>
<td>87 </td>
<td>Espresso </td>
<td>WTF </td>
<td>99 </td>
<td class="rating">4.5 </td>
<td>5 </td>
<td>3 </td>
<td>66 </td>
<td>4 </td>
</tr>
</tbody>
</table>
希望这有助于您朝着正确的方向前进!
哦,我差点忘了!这里是一个jsfiddle的链接,所以你可以看到这个在行动:http://jsfiddle.net/fCpc6/