2016-10-22 91 views
-2

使用JQuery在文檔加載時,我試圖選擇每個<img>並給它一個新屬性title並將其設置爲等於屬性alt的值。 title是用戶在元素上懸停時出現在工具提示中的內容。使用控制檯,我似乎能夠有效地選擇每個元素,但是當我將它們放在一起時,似乎出現了一些問題。如何使用JQuery將一個html屬性的值更改爲不同的屬性值?

的HTML:

<ul class="list"> 

<li><img href="#" src="url" data-toggle="tooltip" data-placement="right" alt="first-tooltip"></li> 

<li><img href="#" src="url" data-toggle="tooltip" data-placement="right" alt="second-tooltip"></li> 

<li><img href="#" src="url" data-toggle="tooltip" data-placement="right" alt="third-tooltip"></li> 

</ul> 

的JS:

$(document).ready(function(){ 
    $('[data-toggle="tooltip"]').tooltip(); //enable tooltips 

    $('.list li').children().each(function(){ //perform function on each <a> 
     var thisAltText = $(this).attr('alt'); //select the alt value 
     $(this).attr('title', thisAltText); //set title value to equal alt value 
    }); 
}); 

正如你所看到的,這是行不通的:http://codepen.io/shawnmurtagh/pen/ZpVgkz

僅供參考 - 我使用.children(),因爲我需要選擇不同的列表項在我的實際項目中。

回答

0

嘗試這樣

$(".list li").each(function() { 
    var thisAltText = $(this).children().attr('alt'); 
    $(this).children().attr('title', thisAltText); 
}); 

或者

$(".list li a").each(function(index) { 
    var thisAltText = $(this).attr('alt'); 
    $(this).attr('title', thisAltText); 
}); 

或者

$(".list li").each(function(index) { 
    var thisAltText = $(this).find('img').attr('alt'); 
    $(this).find('img').attr('title', thisAltText); 
}); 

或者

$(".list").children().each(function(index) { 
    var thisAltText = $(this).find('img').attr('alt'); 
    $(this).find('img').attr('title', thisAltText); 
}); 

在這裏打球https://jsfiddle.net/47jgmzju/

+0

謝謝 - 這是我問的問題的最佳答案。 – smurtagh

0

做這樣的:

$(document).ready(function(){ 
     $('.list li').children().each(function(){ //perform function on each <a> 
      var thisAltText = $(this).attr('alt'); //select the alt value 
      $(this).attr('title', thisAltText); //set title value to equal alt value 
     }); 
     $('[data-toggle="tooltip"]').tooltip(); //enable tooltips 
    }); 
+0

這樣做。在標題已被更改後,需要啓用工具提示。 – smurtagh

+0

@smurtagh很高興,我可以幫忙。你可以將答案標記爲他人蔘考。 – gschambial