从具有相同变量类的元素中获取值
发布了类似的问题,但也许这种情况会更有意义.得到了一个表,其中有许多tr的第一个td,而在另一个tr中有一个重复的第一个td.我正在使用这些进行识别.我想从第二个tr中提取一个值,并将其插入第一个tr中已经附加的(!)td中.这是一个快速的html代码示例
Posted a similar question, but may be this case will make more sense. Got a table with many first td's of tr having a duplicate first td in a different tr. I'm using these for identification. I want to pull a value from 2nd tr and insert it into already appended(!) td in the first tr. Here is a quick html code example
<div class="tableclass">
<table>
<tbody>
<tr>
<td>id1</td>
<td>something else</td>
<td>1</td>
</tr>
<tr>
<td>id2</td>
<td>something else</td>
<td>2</td>
</tr>
<tr>
<td>id2</td>
<td>something else</td>
<td>3</td>
</tr>
<tr>
<td>id3</td>
<td>something else</td>
<td>4</td>
</tr>
<tr>
<td>id1</td>
<td>something else</td>
<td>5</td>
</tr>
<tbody>
</table>
<div>
这是我的jquery代码
And here is my jquery code
$(".tableclass table tbody tr").each(function(){
$(this).append('<td class="fbctr"></td>');
var trclass = $(this).find("td:first-child").html();
$(this).addClass(trclass);
// this is where I'm having a problem
var fbctr = $(this).parent().filter(trclass).eq(2).find("td:nth-child(3)");
$(this).find(".fbctr").html(fbctr);
});
好的,您的问题是jquery
.filter()
在一组给定的DOM元素上起作用.因此,您必须首先选择<tr>
元素,然后使用.filter()
.在您的问题中,您正在将其应用于您的<table>
OK, your problem is that jquery
.filter()
works on a set of given DOM elements. So you have to first select <tr>
elements and then use .filter()
. In your question you are applying it on your <table>
因此,您的JavaScript代码将如下所示:
So, Your JavaScript code will be like this:
$(".tableclass table tbody tr").each(function(){
var trclass = $(this).find("td:first-child").html();
$(this).addClass(trclass);
var fbctr = $(this).parent().find('tr').filter('.'+trclass).eq(1).find("td:nth-child(3)").html();
if(typeof fbctr !== "undefined"){
console.log(fbctr);
$(this).find(".fbctr").html(fbctr);
}
});
更新(更正代码):
如果要将第一出现的元素的值复制到第二出现的元素,请使用以下代码:
In case you want to copy the value of first occurring element into the second occurring element, use this code:
$(".tableclass table tbody tr").each(function(){
var trclass = $(this).find("td:first-child").html();
$(this).addClass(trclass);
var elements = $(this).parent().find('tr').filter('.'+trclass);
if(elements.length > 1){
var fbctr = elements.eq(0).find("td:nth-child(3)").html();
if(typeof fbctr !== "undefined")
$(this).find(".fbctr").html(fbctr);
}
});
如果要将 second 发生元素的值复制到 first 发生元素中,请使用以下代码:
And in case you want to copy the value of second occurring element into the first occurring element, use this code:
$(".tableclass table tbody tr").each(function(){
var trclass = $(this).find("td:first-child").html();
$(this).addClass(trclass);
var elements = $(this).parent().find('tr').filter('.'+trclass);
var fbctr = elements.eq(1).find("td:nth-child(3)").html();
if(typeof fbctr !== "undefined")
$('.'+trclass).not(this).find(".fbctr").html(fbctr);
});