利用 jQuery .children...
var strHtml = $(dt.row(row_idx).child()).children().children().html();
...传入以下 HTML:
<tbody>
<tr>
<td>Notes:</td>
<td>some info</td>
</tr>
<tr>
<td>Assistance Required:</td>
<td>Translation, writing and speaking capabilities </td>
</tr>
<tr>
<td>Unit:</td>
<td>not listed</td>
</tr>
</tbody>
如何抓取标签单元格( <td>Notes:</td>
、 <td>Assistance Required:</td>
、 <td>Unit:</td>
)并移动到下一个对应的值单元格以将 colspan 属性添加到 <td>
然后返回完成的html?
结果应该看起来像......
<tbody>
<tr>
<td>Notes:</td>
<td colspan="12">some info</td>
</tr>
<tr>
<td>Assistance Required:</td>
<td colspan="12">Translation, writing and speaking capabilities </td>
</tr>
<tr>
<td>Unit:</td>
<td colspan="12">not listed</td>
</tr>
</tbody>
最佳答案
获取您的字符串并加载您仅使用该字符串在内存中创建的临时元素。
您可以使用 :nth-child()
伪类选择器仅选择第二个子 <td>
每行中的元素,然后使用 JQuery .attr()
向这些元素添加属性的方法:
var strHTML = `<table>
<tbody>
<tr>
<td>Notes:</td>
<td>some info</td>
</tr>
<tr>
<td>Assistance Required:</td>
<td>Translation, writing and speaking capabilities </td>
</tr>
<tr>
<td>Unit:</td>
<td>not listed</td>
</tr>
</tbody>
</table>`
// Create a temporary element in memory only
var temp = document.createElement("div");
// Load the string into the temp element
$(temp).html(strHTML);
// Now, you can search through the element
$("td:nth-child(2)", temp).attr("colspan", "12"); // Add the attribtue to the second td in each tr
console.log($(temp).html()); // Get the HTML contents of the <table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 使用 jQuery 将属性添加到 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50749491/