【问题标题】:Looking to simplify adding an attribute based on sibling's text希望简化基于兄弟的文本添加属性
【发布时间】:2010-08-03 18:39:39
【问题描述】:

我想为一行添加一个 Title 属性,并且该值是从该行的同级中检索的,该同级是隐藏的,除非单击。当某些屏幕没有带有文本的隐藏行时,我想让它足够通用。

这是第一个有效的过程:

$(function() {
  $("td.commandText pre").each(function(index) {
    $(this).parent().parent().prev().attr('Title', $(this).text());
  });
});

有什么想法可以让它更优雅吗?

这是我正在使用的 HTML 表格的示例:

<table class="maingrid">
  <thead>
    <tr>
      <th>Session ID</th>
      <th>User Name</th>
      <th>Start Time</th>
      <th>End Time</th>
    </tr>
  </thead><tbody>
    <tr class="record">
      <td id="174">174</td>
      <td>user1</td>
      <td>8/2/2010 4:00:09 PM</td>
      <td></td>
  </tr>
  <tr>
     <td class="details hide commandText" colspan="4">
       <pre>Sample Text to show as a tooltip</pre></td>
     </tr>
  <tr>
     <td class="details hide" colspan="4" style="color:red"><pre>no errors</pre></td>
  </tr>
    <tr class="record">
      <td id="175">175</a></td>
      <td>user1</td>
      <td>8/2/2010 4:00:09 PM</td>
      <td></td>
  </tr>
  <tr>
     <td class="details hide commandText" colspan="4">
       <pre>Sample Text to show as a tooltip</pre></td>
     </tr>
  <tr>
     <td class="details hide" colspan="4" style="color:red"><pre>no errors</pre></td>
  </tr>
</tbody>
</table>

【问题讨论】:

  • @Felix - 我认为他只是在解释它的原因,而不是当前代码的问题:)

标签: jquery attr siblings


【解决方案1】:

您可以使用.closest() 使其更短,如下所示:

$(function() {
  $("td.commandText pre").each(function(index) {
    $(this).closest('tr').prev().attr('Title', $(this).text());
  });
});

除此之外,这里没有更多的优雅之处。

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 2019-06-22
    • 1970-01-01
    • 2022-01-09
    • 2021-11-14
    • 1970-01-01
    • 2017-11-09
    • 2019-10-29
    • 1970-01-01
    相关资源
    最近更新 更多