简体   繁体   English

查找img元素并使用js替换为某些内容

[英]find img element and replace with something using js

My source is generated with obvious error in setting align and margin attribute at img element. 我的源代码生成时在img元素上设置align和margin属性时出现明显错误。 So my html src is 所以我的html src是

<p><img left margin: 5px;" src="http://techtools4biz.com/wp-content/uploads/2011/06/Google-logo-300x242-150x150.jpg" alt="" /></p>

ofcourse it should be <img align="left" margin=".." src="..." /> 当然应该是<img align="left" margin=".." src="..." />

In my previous question someone recommended to use find left element which and to replace him with align left property like this 在我之前的问题中,有人建议使用find left元素并将其替换为align left属性,如下所示

$('img'.attr("left")){
    $(this).removeAttr('left');
    $(this).attr("align","left");
};

Tried and it doesn't work, any suggestions? 尝试过并且不起作用,有什么建议吗?

here's the link http://jsfiddle.net/GJRmB/ 这是链接http://jsfiddle.net/GJRmB/

You are mismatching the brackets 您不匹配括号

var $img = $('img');
$img.removeAttr('left');
$img.attr("align","left");

Demo: Fiddle 演示: 小提琴

or use chaining 或使用链接

jQuery(function(){
    var $img = $('img').removeAttr('left').attr("align","left");
})

Demo: Fiddle 演示: 小提琴

If it is guaranteed that the pattern will be always like that, you can use Regex. 如果可以保证模式总是这样,则可以使用Regex。 Actually you should fix whatever generates the source to start with... but lets go... 实际上,您应该修复所有产生源的内容,但是...

Example on JSFiddle JSFiddle上的示例

// the image is wrapped in `p`, so we can easily grab its generated HTML code
var imgMessedHtml = $("img").parent().html();

// now assuming that pattern is always like that, we can try extracting the
// attributes
var align = imgMessedHtml.match(/img (\w+)/i)[1];
var margin = imgMessedHtml.match(/margin.*?(\d+px)/i)[1];

After we get the information we need, we can fix the source 获得所需信息后,我们可以修复源

// I am removing everything between `img` and `src`
$("img").parent().html(
    imgMessedHtml.replace(/img.*?src/i, "img src")
);

Now with the data we extracted we can set it to the img 现在,我们提取的数据可以设置为img

$("img").attr("align", align);
$("img").attr("margin", margin);

Regex is really not recommended to parse HTML , but if you have no other choice then... 确实不建议使用Regex解析HTML ,但是如果您别无选择,那么...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM