首页 > 解决方案 > 使用 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>

标签: javascriptjqueryhtmlhtml-table

解决方案


获取您的字符串并仅使用该字符串加载您在内存中创建的临时元素。

您可以使用: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>


推荐阅读