添加元素<a>在每次<img>之前

Adding element <a> before every <img>

本文关键字:之前 img 元素 添加      更新时间:2023-09-26

我有一个javascript文件创建的HTML代码,这是不可理解的,因为它是使用GWT(Google Web Toolkit)创建的。

<img style="z-index: 6; width: 116px; position: absolute; left: 84px; top: 174px;" src="spiral/sample9.jpg">  
<img style="z-index: 12; width: 197px; position: absolute; left: 0px; top: 161px;" src="spiral/sample1.jpg">
<img style="z-index: 1; position: absolute; left: 659px; top: 213px; width: 85px; opacity: 0.04; display: none;" src="spiral/sample17.jpg">  
<img style="z-index: 1; position: absolute; left: 644px; top: 208px; width: 85px; opacity: 0.08; display: none;" src="spiral/sample18.jpg">

现在我需要在每个图像之前添加标签<a>,使用src,图像的src的一部分。例如:" href="../tmp.php?title=sample9.mp4 "

我该怎么做呢?

我想创建的输出是这样的:

<a href="../tmp.php?title=sample9.mp4"><img style="z-index: 6; width: 116px; position: absolute; left: 84px; top: 174px;" src="spiral/sample9.jpg"></a>

使用jQuery,您可以使用 wrap() 来完成此操作:

$('img').each(function() {
    $(this).wrap($('<a/>', {href: this.src}));
});

您需要的是换行并构建正确的href,您可以使用正则表达式:

$('img').wrap(function(){
    return $('<a>').attr(
        'href',
        '../tmp.php?title=' + this.src.match(/'/(.*?)'.jpg$/)[1] + '.mp4'
    )
});

除了明显缺乏对querySelector函数的理解之外,您还希望</img>能够工作(它没有,它是一个void元素)…

你应该这样做,并注释解释:

var imgs, l, i, img, par, a; // prepare some variables
imgs = document.getElementByTagName('img');
                             // get all images on the page
l = imgs.length;             // save the number of images (for performance reasons)
for( i=0; i<l; i++) {        // loop through all images
    img = imgs[i];           // for easire access
    par = img.parentNode;    // get the parent of the current image
    a = document.createElement('a');
                             // create a new link
    a.href = "../tmp.php?title="+img.src.match(/([^'/.]+'.'w+$/)[1]+".mp4";
                             // extract the right part from the image source
                             // and put it into the link's href
    par.insertBefore(a,img); // insert the link before the image
    a.appendChild(img);      // move the image so that it is inside the link
}