简体   繁体   English

复制图像alt文本并使用jQuery粘贴到div中

[英]Copy image alt text and paste into div with jQuery

I have multiple images on page wrapped with div. 我在页面上有多个用div包装的图像。 I want to copy image alt text and paste it into next img-txt div. 我想复制图像alt文本并将其粘贴到下一个img-txt div中。

<div class="container">
  <img src="kakka.jpg" alt="Text">
  <div class="img-txt"></div>
</div>

<div class="container">
  <img src="kakka2.jpg" alt="Text2">
  <div class="img-txt"></div>
</div>

Problem is that I get first alt text to everywhere. 问题是我得到了第一个alt文本到处。 I know this is easy, but i can't get this working... 我知道这很容易,但我不能让这个工作......

$(".container").each(function(i) {
  var alt = $("img").attr("alt");
  $(".img-txt").text(alt);
});

The issue with your code is, traversing to correct sibling and then getting the alt text. 您的代码的问题是,遍历纠正兄弟,然后获取替代文本。

A smarter solution would be, using callback function of .text() along with traversing to sibling img element here: 一个更智能的解决方案是,使用.text()回调函数以及遍历兄弟img元素:

$(".container .img-txt").text(function() {
   return $(this).siblings('img').attr("alt");
});

Working Demo 工作演示

The issue is because you're selecting all the img and .img-txt elements in each iteration of the loop. 问题是因为您在循环的每次迭代中选择了所有 img.img-txt元素。 Calling attr() on a collection of elements will only retrieve the attribute from the first element in that set. 在元素集合上调用attr()只会从该集合中的第一个元素中检索属性。

You instead need to use the this keyword to reference the current element in the each() loop to find the elements within it: 您需要使用this关键字来引用each()循环中的当前元素以查找其中的元素:

$(".container").each(function() {
  var alt = $(this).find("img").prop("alt");
  $(this).find(".img-txt").text(alt);
});

You can however shorten this by providing a function to text() which is excuted against each matching element instance: 但是,您可以通过为text()提供一个函数来缩短它,该函数针对每个匹配的元素实例执行:

 $(".container .img-txt").text(function() { return $(this).prev('img').prop('alt'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <img src="kakka.jpg" alt="Text"> <div class="img-txt"></div> </div> <div class="container"> <img src="kakka2.jpg" alt="Text2"> <div class="img-txt"></div> </div> 

$(".container").each(function(i) {
  var alt = $(this).children('img').attr("alt");
  $(this).children('.img-txt').text(alt);
});

Try this. 尝试这个。

Here you got another way to copy the alt img into the div: 在这里你有另一种方法将alt img复制到div中:

 $("img").each(function(i) { $(this).next().html($(this).attr("alt")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <img src="kakka.jpg" alt="Text"> <div class="img-txt"></div> </div> <div class="container"> <img src="kakka2.jpg" alt="Text2"> <div class="img-txt"></div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM