【问题标题】:Find the text nearest to an element in HTML content在 HTML 内容中查找最接近元素的文本
【发布时间】:2016-03-20 02:54:59
【问题描述】:

我有一个带有特定标签的 HTML 内容,其中包含文本和图像。 如果我能够选择一张图片并且我想要最接近图片的文字怎么办?

<div class="topStory">
    <div class="photo">
    <a href="somelink"><img src="someimage.jpg" border="0" alt="Photo"></a>
    </div>
    <h2><a href="somelink">Text near to someimage.jpg</a></h2>
    <p>Some extra text.</p>
</div>

在这种情况下,我想要最接近 someimage.jpg 的文本。是否可以使用 PHP 来实现这一点?或者可能是 jQuery?

【问题讨论】:

  • 问之前用过search吗?
  • $('img').closest('.topStory').find('p').text();
  • @JayBlanchard 我被要求向 OP 提供错误信息,并包含 2 个关于 .closet() 的链接我没有掌握什么?我想可能我没有包含.find()
  • @SergioIvanuzzo 您对 Jay 的例子有何看法?
  • .closest() 寻找祖先或父母。要从图像获取其相关文本需要先上(最近)然后再下(查找),因为图像和文本不是彼此的兄弟。

标签: php jquery html-content-extraction


【解决方案1】:

通过最少的 DOM 遍历,您可以选择(单击)图像并找到文本:

<div class="topStory">
    <div class="photo">
    <a href="somelink"><img src="http://placehold.it/350x150" border="0" alt="Photo"></a>
    </div>
    <h2><a href="somelink">Text near to someimage.jpg</a></h2>
    <p>Some extra text.</p>
</div>

jQuery (get the sibling paragraph) UP to .photo 和 ACROSS to h2:

$(document).on('click', 'img', function(e){
    e.preventDefault();
    var associatedText = $(this).closest('.photo').siblings('h2').text();
  console.log(associatedText);
});

如果需要,您也可以去further up the DOM。上至.topStory 下至h2

$(document).on('click', 'img', function(e){
    e.preventDefault();
    var associatedText = $(this).closest('.topStory').find('h2').text();
  console.log(associatedText);
});

这里是每个演示函数的 jQuery 文档:

.closest()
.siblings()
.find()

编辑:基于@guest271314 的良好发现和对OP 问题的重新阅读,我已将p 更改为h2

【讨论】:

  • "在这种情况下,我想要最接近 someimage.jpg 的文本。" .find('p') 应该是 .find('h2') 吗?
  • 是的 - 如果这是您要查找的文本,您会这样做 @guest271314
【解决方案2】:

尝试使用.find().topStory 父元素中选择img;选择不是 .topStoryimg 元素的父级;选择与先前选择的img父元素相邻的第一个元素,在返回的元素上调用.text()

var topStory = $(".topStory");
var img = topStory.find("img");
// here `img.parents().not(topStory)` is `context`
var text = $("~ *:first", img.parents().not(topStory)).text();
console.log(img, text)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="topStory">
    <div class="photo">
    <a href="somelink"><img src="someimage.jpg" border="0" alt="Photo"></a>
    </div>
    <h2><a href="somelink">Text near to someimage.jpg</a></h2>
    <p>Some extra text.</p>
</div>
jsfiddle http://jsfiddle.net/3cvh5rk5/

【讨论】:

  • 为什么 OP 应该尝试这个? 好的答案将始终解释所做的事情以及这样做的原因,不仅适用于 OP,也适用于 SO 的未来访问者。
  • @JayBlanchard 查看更新后的帖子。 stacksn-ps 在作曲时失败了,将创建一个 jsfiddle
  • @JayBlanchard 将 topStory 替换为 top 以不与 window.top 冲突。对方法的解释是否充分?
  • 看起来好多了。
猜你喜欢
  • 2012-01-25
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
相关资源
最近更新 更多