簡體   English   中英

在<a>標簽</a>上創建“標題”屬性

[英]Create “title” attribute on <a> tag

我的HTML代碼的一部分是根據我的JavaScript代碼創建的,更確切地說,是標記<a>的屬性( hreftitle )。
我正在嘗試在<a>內創建HTML title ,以便獲得鼠標懸停效果,並顯示Title和Description。
根據我的javascript代碼, myTitle數組將為每個圖像顯示標題,並將根據其位置顯示...

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]
    })
});

現在的問題是,我無法在attr內創建for循環,因此無法為每個圖像打印myTitle [0],myTitle [1]和myTitle [2] ...

您有什么想法可以繞過這個問題嗎?

請注意, myTitlemyDescr數組是可變的,並且可以myDescr IMAGES ...

使用.each()怎么樣?

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

您可以通過在wrap回調函數中使用index參數來做到這一點。

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

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

演示版

.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
    })
});

演示版

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM