我的部分 HTML 代码是根据我的 javascript 代码创建的,更准确地说是标签 <a>
的属性( href
和 title
)。
我正在尝试创建一个 HTML title
里面<a>
所以我可以有鼠标悬停效果,并显示标题和描述。
根据我的 javascript 代码,myTitle
array 将为每张图像设置标题,并根据其位置显示...
HTML代码
<a href="../test/top.php?title=sample1.mp4" title="Título 1 Descript 1">
<img style="z-index: 20; position: absolute; left: 365px; top: 63px; width: 189px;" src="spiral/sample1.jpg">
</a>
<a href="../test/top.php?title=sample2.mp4" title="Título 1 Descript 1" >
<img style="z-index: 17; position: absolute; left: 674px; top: 60px; width: 155px;" src="spiral/sample2.jpg">
</a>
JavaScript 代码
var myTitle = ["Title 1", "Title 2", "Title 3"];
var myDescr = ["Desc 1", "Desc 2", "Desc 3"];
$('img').wrap(function(){
return $('<a>').attr({
href:
'../test/top.php?title=' + this.src, title: myTitle[0] + "\n" + myDescr[0]
})
});
现在的问题是我无法创建 for
attr
里面的循环所以我无法为每张图片打印 myTitle[0]、myTitle[1] 和 myTitle[2]...
有什么想法可以绕过这个问题吗?
请注意 myTitle
一个myDescr
数组是可变的,图像可以重复...
最佳答案
你可以这样做,使用 wrap 中的索引参数回调函数。
$('img').wrap(function (i) {
return $('<a>').attr({
href:
'../test/top.php?title=' + this.src,
title: myTitle[i] + "\n" + myDescr[i]
})
});
Demo
.wrap( function(index) )
如果您希望标题/描述在重复图像中重复出现,请尝试这种方式。
var myTitle = ["Title 1", "Title 2", "Title 3"];
var myDescr = ["Desc 1", "Desc 2", "Desc 3"];
$('img').wrap(function (i) {
var title = myTitle.shift(); //Get the top
myTitle.push(title); //push back for cycle
var descr = myDescr.shift();//Get the top
myDescr.push(descr);//push back for cycle
return $('<a>').attr({
href:
'../test/top.php?title=' + this.src,
title: title + "\n" + descr
})
});
Demo
关于javascript - 在 <a> 标签上创建 "title"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16922605/