从字符串中选择td

时间:2017-01-04 09:24:55

标签: javascript jquery css

我将以下Html搅拌存储在JS变量中:

<td>
  <input onclick="Clicked(this);" type="radio" name="mmBox" id="mmBox">
</td>
<td>First Cell</td>
<td>2nd TD</td>
<td>3rd TD</td>
<td>4th TD</td>
<td>5th TD</td>
<td></td>

我根据需要选择第2,第3和第4 <td>

我已经尝试了以下但它没有返回任何内容:

console.log("6 " + $(selectedRow).wrap("<tr></tr>").children("td:nth-child(2)").html());

console.log("6 " + $(selectedRow).find("td:eq(2)").text());

即使使用.find.select方法,也不会返回任何内容。

请帮助我,我想查询<td>及其中的值

3 个答案:

答案 0 :(得分:2)

假设selectedRow变量包含您发布的html字符串,则应使用.filter方法而不是.find

$(selectedRow).filter(":eq(2)").text();

或者使用.eq方法:

$(selectedRow).eq(1).text();

请注意.eq从零开始,因此1选择集合中的第二个元素。

答案 1 :(得分:2)

wrap()方法将每个td换成单独的tr元素,我认为您需要一个tr来包装该用途的所有元素wrapAll()方法。虽然使用filter()方法,因为您需要从jQuery元素中过滤掉td而不是从子元素中过滤掉tr。实际上,如果您只想获取内容,则完全不需要使用var selectedRow = '<td><input onclick="Clicked(this);" type="radio" name="mmBox" id="mmBox"></td><td>First Cell</td><td>2nd TD</td><td>3rd TD</td><td>4th TD</td><td>5th TD</td><td></td>'; console.log("6 " + $(selectedRow).wrapAll("<tr></tr>").filter("td:nth-child(2)").html()); // by removing code which wraps the elements console.log("6 " + $(selectedRow).filter("td:nth-child(2)").html());包装。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
func_range(5) :     print 1 to 5 
func_range(1 , 5) : print 1 to 5
func_range() : print "please set the argument"

答案 2 :(得分:2)

反过来......先创建一个行元素然后在该行中设置单元格,然后在行对象上使用find

var $row = $('<tr>').html(selectedRow);
console.log("6 " + $row.find("td:eq(2)").text());
相关问题