首页 > 解决方案 > 用下一个 onLoad 的 id 替换 this 的内容

问题描述

给定下表,第一个<td>的内容应该替换为下一个td.inputid拆分id后的第二个值)。

<table>
  <colgroup>
    <col width="100" />
    <col width="100" />
  </colgroup>
  <tbody>
    <tr>
      <td>Element</td>
      <td>Value</td>
    </tr>
    <tr>
      <td><span>one</span></td>
      <td id="test"><span><input id="rjaxWMQBmoH-HllvX50cXC0-val" name="entryfield" title="element" value="[ one ]"     /></span></td>
    </tr>
  </tbody>
</table>

这样第一个<td>就变成<td><span>HllvX50cXC0</span></td>了负载。我可以看到$(this).next()下面列出的方法,lastChildren但我想知道这是否是正确的方法?

标签: jqueryhtml

解决方案


你的问题和你的标记有几个方面,这使得这有点不太清楚,但下面评论的 jQuery 可以满足你的要求。

// no-conflict-safe document ready
jQuery(function($) {
  // loop through all inputs contained inside of a td
  $('td input').each(function() {
    // load the id of the input
    var id = $(this).attr('id');
    // if the id exists, and has a - in it, then....
    if (id && id.indexOf('-') > 0) {
      // split the id into parts (regex would also work here)
      id = id.split('-');
      // get the second part of the id
      id = id[1];
      // put the id into the previous cell's contents
      $(this).closest('td').prev('td').find('span').text(id);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <colgroup>
    <col width="100" />
    <col width="100" />
  </colgroup>
  <tbody>
    <tr>
      <td>Element</td>
      <td>Value</td>
    </tr>
    <tr>
      <td><span>one</span></td>
      <td id="test"><span><input id="rjaxWMQBmoH-HllvX50cXC0-val" name="entryfield" title="element" value="[ one ]"     /></span></td>
    </tr>
  </tbody>
</table>

有几种方法可以切片,这只是一种。

jQuery 的关键是使用好的选择器,以及对首选 DOM 导航功能的清晰理解。我强烈推荐最接近查找(而不是parentparents and children,它们有通过使用最接近 / find 避免的陷阱)。


推荐阅读