在<a> tag</a>上创建“标题”属性

时间:2013-06-04 16:09:33

标签: javascript jquery html

我的部分HTML代码是根据我的javascript代码创建的,更准确地说是标记<a>hreftitle)的属性。
我正在尝试在title内创建HTML <a>,因此我可以使用鼠标悬停效果,并显示标题和说明。
根据我的javascript代码,myTitle数组将为每个图像添加标题,并将根据其位置显示...

HTML CODE

<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 CODE

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]每一张图片......

我可以绕过这个问题吗?

请注意,myTitlemyDescr数组是可变的,图像可以重复...

2 个答案:

答案 0 :(得分:3)

如何使用.each()

$('img').each(function(i) {
    $(this).wrap(function(){
        return $('<a>').attr({
            href: '../test/top.php?title=' + this.src, title: myTitle[i] + "\n" + myDescr[i]
        });
    });
});

答案 1 :(得分:3)

你可以这样做,使用wrap回调函数中的index参数。

$('img').wrap(function (i) {

    return $('<a>').attr({
        href:
            '../test/top.php?title=' + this.src,
        title: myTitle[i] + "\n" + myDescr[i]
    })
});

Demo

  

.wrap(function(index))

如果您希望标题/ desc重复播放重复图像,请尝试这种方式。

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

相关问题