我有一个html格式的变量。 我想从它获得第一个IMG标签。 有一个简单的方法吗?
var x = "my name is name picture <img src='/img/pic.a' alt='here first pic'><br/>second pic is here <img src='/img/pic.b' alt='this is the second place'> and the third pic <img src='/img/pic.a' alt='pic 3'> <table><tr><td>first coloumn</td><td>second coloumn</td></tr><tr><td>2first coloumn</td><td>2second coloumn</td></tr></table><br/><p>here is it</p><br><a href='/home'>click here</a>.<br/> end";
var pictureNumber = 1;
var z = x.split("<img")[pictureNumber].split(">");
$("#strImg").val("<img" + z[0] + "/>");
小提琴是here
更新 感谢@Tushar的建议,它更简单。 根据他的建议工作繁琐here 希望对他人有用
答案 0 :(得分:2)
您可以使用正则表达式进行提取。
/(<img[^>]+>)/gi
正则表达式说明:
()
:捕获组以访问匹配的结果<img
:按字面意思匹配<img
[^<]+
:匹配任何非<
>
:匹配>
,图片标记的结尾gi
:g:全局匹配,i:不区分大小写的匹配
var x = "my name is name picture <img src='/img/pic.a' alt='here first pic'><br/>second pic is here <img src='/img/pic.b' alt='this is the second place'> and the third pic <img src='/img/pic.a' alt='pic 3'> <table><tr><td>first coloumn</td><td>second coloumn</td></tr><tr><td>2first coloumn</td><td>2second coloumn</td></tr></table><br/><p>here is it</p><br><a href='/home'>click here</a>.<br/> end";
var z = x.match(/(<img[^>]+>)/gi);
console.log(z);
$("#strImg").val(z[0]);
document.getElementById('result').innerText = JSON.stringify(z, 0, 4);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="strImg" size=50>
<br /><br />
<hr />
All Images:
<pre id="result"></pre>
&#13;
答案 1 :(得分:0)
你走了:
HTML:
<div id="mydiv">my name is name picture <img src='/img/pic.a' alt='here first pic'><br/>second pic is here <img src='/img/pic.b' alt='this is the second place'> and the third pic <img src='/img/pic.a' alt='pic 3'> <table><tr><td>first coloumn</td><td>second coloumn</td></tr><tr><td>2first coloumn</td><td>2second coloumn</td></tr></table><br/><p>here is it</p><br><a href='/home'>click here</a>.<br/> end</div>
Javascript:
$("#strImg").val($("#mydiv").children().first()[0].outerHTML);
答案 2 :(得分:0)
没有惊人的做法,但有一种方式:
$(document).ready(function() {
var x = "my name is name picture <img src='/img/pic.a' alt='here first pic'><br/>second pic is here <img src='/img/pic.b' alt='this is the second place'> and the third pic <img src='/img/pic.a' alt='pic 3'> <table><tr><td>first coloumn</td><td>second coloumn</td></tr><tr><td>2first coloumn</td><td>2second coloumn</td></tr></table><br/><p>here is it</p><br><a href='/home'>click here</a>.<br/> end";
$("#strImg").val(getImageTag(x, 2));
});
function getImageTag(x, offset) {
var imgTag = '';
var raw = x;
for (i = 0; i < offset; i++) {
var imgIndex = raw.indexOf('<img');
var imgEndIndex = raw.substring(imgIndex).indexOf('>');
imgTag = raw.substring(imgIndex).substring(0, imgEndIndex + 1);
raw = raw.substring(imgEndIndex + 1);
}
return imgTag;
}
检查jsfiddle:
https://jsfiddle.net/JoshB1997/rpjh3yLo/6/
偏移量是你要获得的img标签(1 =第一,2 =第二等...) 您还可以先获取所有图像标记,存储在数组中,然后使用索引获取图像。但只有jQuery,我认为这不可能。