[英]How to get value from inside <li> element and put it to image attribute tag using jQuery
I want to get the value from H3 element and put it to image attribute such as title and alt. 我想从H3元素中获取值并将其放入图像属性,例如title和alt。 please see my code below.
请看下面的代码。
$('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>
Try this: 尝试这个:
$(".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
});
$(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.