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

时间:2013-08-24 13:34:08

标签: javascript jquery

在img元素中设置align和margin属性时,生成了明显错误的源代码。所以我的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="..." />

在我之前的问题中,有人建议使用查找左侧元素,并将其替换为左侧属性,如此

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

尝试过,它不起作用,有什么建议吗?

这是链接 http://jsfiddle.net/GJRmB/

3 个答案:

答案 0 :(得分:1)

您的括号

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

演示:Fiddle

或使用链接

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

演示:Fiddle

答案 1 :(得分:1)

您可以使用链接和 the attribute selector

$('img[left]').removeAttr('left').attr("align","left");

jsFiddle here

请参阅aslso:

答案 2 :(得分:1)

如果确保模式始终如此,则可以使用Regex。实际上你应该修复任何产生源的东西......但是让我们去......

Example on 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];

在我们获得所需信息后,我们可以修复源

// 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,但如果您别无选择,那么......

相关问题