【问题标题】:How to get text to attribute from current tag only, not from all tags in page?如何仅从当前标签获取文本属性,而不是从页面中的所有标签?
【发布时间】:2020-11-12 22:14:25
【问题描述】:

我正在尝试从中获取文本并自动添加到用于灯箱的属性“数据标题”。事实上,一切正常,不幸的是,页面上有几个表格,所以属性从所有表格中获取文本。如何修复,仅在当前表格中设置属性中的文本。

var y = $(".tr-caption_2020").text(function());
$(".img_2020").attr("data-title", y);

<table class="tr-caption-container_2020"><tbody>
<tr>
<td>
<a class="img_2020" data-lightbox="stage1" href="pic.png">
<img src="/s400/pic.png" /></a>
</td>
<td class="tr-caption_2020">text text text.</td>
</tr>
</tbody></table>

【问题讨论】:

  • 您能否为.tr-caption_2020.img_2020 元素显示您的html

标签: javascript jquery lightbox attr


【解决方案1】:

在您的具体情况下,您可以这样做:

$("[class^=tr-caption_]").each(function(i) {
    var thisLabel = $(this);
    var thisClass = thisLabel.attr('class');
    var thisNumber = thisClass.replace('tr-caption_', '');
    var thisText = thisLabel.text();
    $('.img_'+thisNumber).attr("data-title", thisText);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tr-caption-container_2020">
  <tbody>
    <tr>
      <td>
        <a class="img_2020" data-lightbox="stage1" href="pic.png">
          <img src="/s400/pic.png" /></a>
      </td>
      <td class="tr-caption_2020">text text text.</td>
    </tr>
  </tbody>
</table>

同样在JSFiddle

但我会建议其他方式,因为您实际上使用类作为 ID,这非常没用 - 使用 ID 或数据属性。

如果您在代码中使用相同的类,那么您可以简单(并且更快,使用干净的选择器)do this

$(".lightbox-img").each(function(i) {
    var thisImg = $(this);
    var thisTitle = $(this).closest('tr').find('.lightbox-caption').text();
    thisImg.attr('data-title', thisTitle);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>
        <a class="lightbox-img" data-lightbox="stage1" href="pic.png">
          <img src="/s400/pic.png" /></a>
      </td>
      <td class="lightbox-caption">text text text.</td>
    </tr>
  </tbody>
</table>

为了进一步阅读,我建议Optimize Selectors,我们可以在哪里找到:

尽可能避免包含 jQuery 扩展的选择器。这些 扩展不能利用提供的性能提升 本机 querySelectorAll() DOM 方法,因此需要 使用 jQuery 提供的 Sizzle 选择器引擎。

【讨论】:

  • 您可以/应该检查它/接受它作为未来读者的答案,干杯。
【解决方案2】:

这是一个香草JS的sn-p,希望对你有帮助!

const tableRows = document.querySelectorAll('.tr-caption-container_2020 tr');

tableRows.forEach(tr => {
  const cellWithText = tr.querySelector('.tr-caption_2020');
  const cellText = cellWithText.textContent;
  const imageInCell = tr.querySelector('.img_2020 img');
  imageInCell.setAttribute('data-title', cellText)
});
<table class="tr-caption-container_2020">
  <tbody>
    <tr>
      <td>
        <a class="img_2020" data-lightbox="stage1" href="pic.png">
          <img src="/s400/pic.png" />
        </a>
      </td>
      <td class="tr-caption_2020">text text text.</td>
    </tr>
  </tbody>
</table>

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多