克隆文本并插入壁橱标题范围

时间:2015-07-05 12:15:29

标签: jquery

我有一个包含多个表的页面,所有表格都有不同的文字,我想克隆该文本并将其放在标题中。

我尝试了这个,但它会拉出每一个文字并放入每个标题

$( 'caption span' ).each(function( index ) {
  $(this).text($('th').text());
});

HTML示例

<table class="report"><caption><span>Place New Text Here For This Tables th</span></caption><tbody><tr><th>Clone This Text #1</th></tr>
</tbody></table>

<table class="report"><caption><span>Place New Text Here For This Tables th</span></caption><tbody><tr><th>Clone This Text #2</th></tr>
</tbody></table>

1 个答案:

答案 0 :(得分:2)

  1. 使用closest()
  2. 导航到容器表
  3. 使用find()获取表th
  4. &#13;
    &#13;
    $('caption span').each(function(index) {
      $(this).text($(this).closest('table').find('th').text());
    });
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <table class="report">
      <caption><span>Place New Text Here For This Tables th</span>
      </caption>
      <tbody>
        <tr>
          <th>Clone This Text #1</th>
        </tr>
      </tbody>
    </table>
    
    <table class="report">
      <caption><span>Place New Text Here For This Tables th</span>
      </caption>
      <tbody>
        <tr>
          <th>Clone This Text #2</th>
        </tr>
      </tbody>
    </table>
    &#13;
    &#13;
    &#13;