添加元素<a>在每次<img>之前
Adding element <a> before every <img>
我有一个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
}
相关文章:
- ZeroClipboard-在复制之前添加到值
- 如何更改<svg>标记为<img>用js标记
- JQuery添加元素需要在我的js之前再次添加JQuery脚本
- 在Safari执行javascript之前对其进行修改
- 为什么在变形之前不缺少Fx
- 有没有一种方法可以防止img get请求使用css或js发生
- Javascript:使用绝对路径设置img src
- Chrome扩展没有't在重新加载之前考虑期权价值
- 循环结束/推送到数组之前在页面上呈现EJS
- 在数据提取完成之前进行页面渲染
- Setting default onclick behavior for <img> tag in gene
- 在Highcharts中,我们可以通过任何方式在渲染图表之前获得plotWidth和plotHeight
- 未捕获错误:无法在初始化之前调用方法;
- 在页面呈现之前更改HTML数据
- 在动画结束之前调用函数
- 在显示之前设置 img 的大小
- Javascript - 在加载图像之前触发 img onload
- jQuery获取src更改后和fadeIn之前的img宽度
- 在将图像分配给img标记之前,请使用javascript调整图像大小
- 在发送到 BASE64 之前调整图像大小(不使用 img 元素)