找到最接近HTML内容中

时间:2015-12-14 15:03:49

标签: php jquery html-content-extraction

我有一个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?

2 个答案:

答案 0 :(得分:3)

使用最少的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到.photo和ACROSS到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

答案 1 :(得分:0)

尝试使用.find()img父元素中选择.topStory;选择不是img的{​​{1}}元素的父元素;选择与之前选择的.topStory父元素相邻的第一个元素,在返回的元素上调用img

&#13;
&#13;
.text()
&#13;
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)
&#13;
&#13;
&#13; jsfiddle http://jsfiddle.net/3cvh5rk5/