簡體   English   中英

如何從內部獲取價值 <li> 元素並使用jQuery將其放入圖像屬性標記

[英]How to get value from inside <li> element and put it to image attribute tag using jQuery

我想從H3元素中獲取值並將其放入圖像屬性,例如title和alt。 請看下面的代碼。

 $('ul.products').each(function() { $(this).find('li h3').each(function() { var current = $(this); if (current.children().size() > 0) { return true; } console.log($(this).text()); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul class="products"> <li> <a href="#"> <img src="/path/" title="(Get value from h3)" alt="(Get value from h3)"> </a> <h3>Mytitle1</h3> </li> <li> <a href="#"> <img src="/path/" title="(Get value from h3)" alt="(Get value from h3)"> </a> <h3>Mytitle2</h3> </li> <li> <a href="#"> <img src="/path/" title="(Get value from h3)" alt="(Get value from h3)"> </a> <h3>Mytitle3</h3> </li> </ul> 

嘗試這個:

$(".products li").each(function() { // loop through all the li
  var txt = $(this).find("h3").text(); // find the h3 tag and get its  text
  $(this).find("img").attr("title",txt); // set title of image
  $(this).find("img").attr("alt",txt); // set alt of image
});

嘗試:

$('ul.products').each(function(){
    $(this).find('li h3').each(function(){//loop the h3
          $(this).prev('a').find('img').attr({'title':$(this).text(),'alt':$(this).text()});//get the image usin prev and find add the atributes to it
    });

});

演示

您可以使用prev查找上a標記並找到找到img元素然后使用attr添加屬性

 $(this).prev('a').find('img').attr({
              'title':_getText,
              'alt':_getText
              }) 

的jsfiddle

 $(function() { $('.products li').each(function() { var item = $(this); var text = item.find('h3').text(); item.find('img').attr({ 'title': text, 'alt': text }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul class="products"> <li> <a href="#"><img src="/path/" title="(Get value from h3)" alt="(Get value from h3)"> </a> <h3>Mytitle1</h3> </li> <li> <a href="#"><img src="/path/" title="(Get value from h3)" alt="(Get value from h3)"> </a> <h3>Mytitle2</h3> </li> <li> <a href="#"><img src="/path/" title="(Get value from h3)" alt="(Get value from h3)"> </a> <h3>Mytitle3</h3> </li> </ul> 

暫無
暫無

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

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