javascript - 使用 jQuery 向 HTML 元素添加属性
问题描述
使用 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 - 用JS查找和替换自定义格式文本中的文本
- keras - 组合 GAN 函数期望输入轴为 -1。在 Jupyter 中工作而不在 Colab 中工作
- c - 为什么我的程序在定义两个大数组时会崩溃?
- excel - 有没有办法使用 TEXTJOIN 并增加分隔符?
- css - 任何人都知道如何删除输入中的丑陋框
- azure - 在应用程序洞察中捕获 APIM 请求和响应有效负载的正确方法是什么?
- amazon-web-services - EKS pod 中的多个卷挂载
- c++ - 等待 MyService 服务连接时达到超时(45000 毫秒)
- javascript - 有没有一种巧妙的方法来分隔 JS/jquery 中的选中复选框标签?
- r - 根据列值删除分组后的行