2

如何从 INPUT VAR HTML 有条件地获取 IMG 属性,例如 SRC、ALT、HEIGHT、WEIGHT,然后执行就地替换,以便只有 IMG 标签受到影响,而 HTML 的其余部分应保持不变......

我怎么能在 js/jquery 中做到这一点......?

健康)状况

if images->getAttribute('width') > 18 && images->getAttribute('width')< 640)

输入:

html='<p>some text</p>
<p><img src="image_1.jpg" width="630" height="380" alt="image_1"></p>
<p>some more text</p>
<p><img src="image_2.jpg" width="18" height="18" alt="image_2"></p>';

输出:

html='<p>some text</p>
<p><a class="test" title="image_1" href="image_1.jpg" rel="image_1">
<img width="630" height="380" alt="" src="image1.jpg" ></a></p>
<p>some more text</p>
<p><img src="image_2.jpg" alt="image 2" width="18" height="18"></p>';
4

1 回答 1

1

你可以这样做(使用jquery):

$html = $(html);

//For each img in html
$html.find('img').each(function() {
    $img = $(this);

    //Your own logic
    if ($img->attr('width') > 18 && $img->attr('width') < 640) {
        //We create our a link
        $a = $('<a class="test" title="' 
            + $img.attr('title') + '" alt="' 
            + $img.attr('title') + '" href="' 
            + $img.attr('src') + '"></a>');

        //We add a cone of the original image into our a
        $a.append($img.clone());
    }

    //We replace our image by our a link
    $img.replaceWith($a);
});

//We get the new html string
html = $html.html();
于 2013-07-05T12:43:37.903 回答