javascript - 处理html字符串的正则表达式
大家讲道理
大家讲道理 2017-04-10 14:56:41
[JavaScript讨论组]

不是很会使用正则表达式,求各位帮忙看下一个需求

有一段html的字符串,如下

html<p>看<span style="font-size: 15px; line-height: 1.5;">图说话</span></p>
<p><img src="http://a.com/1.png" alt=""></p>
<p> </p>
<p> </p>
<p>再来一张图片</p>
<p><img src="http://a.com/2.png" alt="" width="609" height="590"></p>

需要能够针对字符串中的img标签做如下处理:
1. 加上 width="100%" height="auto",如果img已经存在width和hegiht,需要先去掉
2. 增加一个onlick事件,传入img的src作为参数

期待的结果是

html<p>看<span style="font-size: 15px; line-height: 1.5;">图说话</span></p>
<p><img src="http://a.com/1.png" alt="" width="100%" height="auto" onlick="foo('http://a.com/1.png')"></p>
<p> </p>
<p> </p>
<p>再来一张图片</p>
<p><img src="http://a.com/2.png" alt="" width="100%" height="auto" onlick="foo('http://a.com/2.png')"></p>
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
PHPz
var str = '<p>看<span style="font-size: 15px; line-height: 1.5;">图说话</span></p>\
    <p><img src="http://a.com/1.png" alt=""></p>\
    <p> </p>\
    <p> </p>\
    <p>再来一张图片</p>\
    <p><img src="http://a.com/2.png" alt="" width="609" height="590"></p>';

function query( str, callback ) {
    var d = document.createElement("p");
    d.innerHTML = str;
    return callback( d );
}

str = query( str, function( dom ) {
    [].forEach.call( dom.querySelectorAll(dom), function(img) {
        img.setAttribute("width", "100%"),
        img.setAttribute("height", "auto"),
        img.setAttribute("onclick", "foo('"+ img.src +"')")
    })
    return dom.innerHTML;
})
怪我咯

Regex不太會, 但是用JavaScript還是可以的.

js(function(){
  $('img').each(function(){
    $this = $(this);
    $this.attr({
        width: '100%',
        height: 'auto',
        onclick: "foo('" + $this.attr('src') + "')"
    });
  });
}());
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号