如何从<li>元素中获取值并使用jQuery将其放入图像属性标记中

时间:2016-06-01 05:59:07

标签: javascript 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>

4 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

尝试:

$('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
    });

});

demo

答案 2 :(得分:0)

您可以使用prev查找之前的a代码和find来查找img元素&amp;然后使用attr添加属性

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

jsfiddle

答案 3 :(得分:0)

$(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>