我的源代码在设置 img 元素的对齐和边距属性时存在明显错误。所以我的 html src 是
<p><img left margin: 5px;" src="http://techtools4biz.com/wp-content/uploads/2011/06/Google-logo-300x242-150x150.jpg" alt="" /></p>
当然应该是<img align="left" margin=".." src="..." />
在我之前的问题中,有人建议使用 find left 元素并将其替换为像这样的align left 属性
$('img'.attr("left")){
$(this).removeAttr('left');
$(this).attr("align","left");
};
尝试过,但不起作用,有什么建议吗?
最佳答案
如果保证模式始终是这样,则可以使用正则表达式。实际上,您应该修复生成源代码的任何内容……但是让我们走吧……
// 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];
获得所需信息后,我们可以修复源
// I am removing everything between `img` and `src`
$("img").parent().html(
imgMessedHtml.replace(/img.*?src/i, "img src")
);
现在,使用我们提取的数据,我们可以将其设置为 img
$("img").attr("align", align);
$("img").attr("margin", margin);
Regex is really not recommended to parse HTML ,但如果你别无选择那么......
关于javascript - 找到 img 元素并使用 js 替换为某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18419146/