使用javascript/jQuery从HTML字符串中获取属性值

DB.*_*DB. 9 javascript jquery attributes

我有一个包含文本和图像的HTML字符串,例如

<p>...</p>
<img src="..." />
<p>...</p>
Run Code Online (Sandbox Code Playgroud)

我需要获取第一个图像的src属性.图像可能会或可能不会在a之后出现,<p>并且可能存在多个图像,或者根本没有图像.

最初,我尝试将字符串附加到DOM并进行过滤.但是,如果我这样做,浏览器会请求所有外部资源.在我的情况下,这增加了许多不必要的开销.

我的初步方法:

var holder = $('<div></div>'); 

holder.html(content);

var src = holder.find('img:first').attr('src'); 
Run Code Online (Sandbox Code Playgroud)

如何在不附加HTML的情况下获取第一张图像的src?我需要使用正则表达式,还是有更好的方法?

解决方案需要基于javascript/jQuery - 我没有使用任何服务器端语言.

我的问题非常类似于:http://forum.jquery.com/topic/parsing-html-without-retrieving-external-resources

谢谢

Dav*_*ith 12

这个

$("<p><blargh src='whatever.jpg' /></p>").find("blargh:first").attr("src")
Run Code Online (Sandbox Code Playgroud)

回来whatever.jpg所以我想你可以试试

$(content.replace(/<img/gi, "<blargh")).find("blargh:first").attr("src")
Run Code Online (Sandbox Code Playgroud)

编辑

/<img/gi 代替 "<img"


Bra*_*one 5

这应该工作:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        //Document Ready: Everything inside this function fires after the page is loaded
        $(document).ready(function () {
                    //Your html string
            var t = "<p><img src='test.jpg'/></p>"
            alert($(t).find('img:first').attr('src'));
        });
    </script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


小智 5

我通常使用以下内容:

$(content).attr("src")
where 
content = "img src='/somesource/image.jpg'>" //removed < before img for html rendering in this comment
Run Code Online (Sandbox Code Playgroud)