在两个图像之间获取文本 [英] get text between two images

查看:65
本文介绍了在两个图像之间获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种更简单的方法来捕捉两个图像之间的文本,这些图像没有相同的父元素?
我正在为一个网页制作一个脚本。
赞:

 < div id =content>< / div> 
< div style =text-align:center>< img src =alt =>< / div>
< a>一些文字< / a>
< img src =alt =>
< div style =text-align:left>更多文字< / div>
< / div>

如何获取div内容的第一张图片和第二张图片之间的文字。我不知道完全正确的结构,因为可能文本和图像可能在div或节点内。我宁愿不使用库

解决方案

您基本上要处理< img> 标签标记为要提取的文本周围的引号。



最简单的方法是替换< img> ; 标签,在文本中不可能重复,并将该字符用作分隔符。我会告诉你如何使用jQuery。如果你需要它在纯JS中完成比你不得不转换它。



首先制作一份HTML副本。

  var html = $('< div>)。append($(#content)。html()); 

接下来,将所有< img>

  html.find(img)。replaceWith( < DIV>〜< / DIV> 中); 

一旦你完成了,你可以在这些分隔符之间匹配文本。

  var str = html.text(); 
var rx = /〜([^〜] +)〜/ g;
var match = rx.exec(str);

要查找所有匹配项,请重复。

<$ (匹配!=空)
{
alert(match [1]); p $ p>
match = rx.exec(str);

$ / code>

可以用一个独特的短语来做同样的事情,比如 @img @ 代替单个字符,但单个字符更容易。



这是一个可用的小提琴。



http://jsfiddle.net/thinkingmedia/etx1z6ov/2/


Is there a simpler way to catch the text between two images which haven't a same parent element? I'm making a userscript for a webpage. Like:

<div id="content"></div>
     <div style="text-align:center"><img src="" alt=""></div>
     <a>some text</a>
     <img src="" alt="">
     <div style="text-align:left">more text</div>
</div>

How to get the text between the 1st image and 2nd image of the div content. I don't know exactly the correct structure because maybe the text and the images could be inside of div or a nodes. I'd rather not use libraries

解决方案

You basically want to handle the <img> tags as quotes around text you want to extract.

The easiest way to do that is to just replace the <img> tag with something not likely repeated in the text, and use that character as a delimiter. I'll show you how using jQuery. If you need it done in pure JS than you'll have to convert this.

First, make a copy of the HTML.

var html = $('<div>').append($("#content").html());

Next, replace all <img> tags with a special character (or other token you know is unique).

html.find("img").replaceWith("<div>~</div>");

Once you've done that you can just match text between those delimiters like this.

var str = html.text();
var rx = /~([^~]+)~/g;
var match = rx.exec(str);

To find all matches just repeat.

while(match != null)
{
    alert(match[1]);
    match = rx.exec(str);    
}

It's possible to do the same with a unique phrase like @img@ instead of a single character, but a single character is way easier.

Here's a working fiddle.

http://jsfiddle.net/thinkingmedia/etx1z6ov/2/

这篇关于在两个图像之间获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆