【问题标题】:Adding Attribute to HTML element with jQuery使用 jQuery 向 HTML 元素添加属性
【发布时间】:2018-06-08 05:45:11
【问题描述】:

利用 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>

如何抓取标签单元格(&lt;td&gt;Notes:&lt;/td&gt;&lt;td&gt;Assistance Required:&lt;/td&gt;&lt;td&gt;Unit:&lt;/td&gt;)并移动到其下一个对应的值单元格以将 colspan 属性添加到 &lt;td&gt;,然后返回完成的 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>

【问题讨论】:

  • 我假设您无权访问生成 html 的代码?
  • 正确,我无权访问生成 html 的代码。

标签: javascript jquery html html-table


【解决方案1】:

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

您可以使用 :nth-child() 伪类选择器只选择每行中的第二个子 &lt;td&gt; 元素,然后使用 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>
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 我对此很陌生,所以我不知道td:nth-child(2),但是如何针对我的变量strHtml 中的HTML 运行它,因为我需要使用调整后的HTML 返回变量?
  • 所以即使这是不正确的,在我看来伪代码类似于strHtml = $(strHTML).$("td:nth-child(2)").attr("colspan", "12");
猜你喜欢
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多