将图像src中的链接复制为文本

时间:2017-11-17 11:49:21

标签: jquery

我有一个列表,其中每个li都有一些图像,我正在尝试将每个img src=复制为纯文本到.someDiv

HTML

<ul class="someList">
  <li><a href=""><img src="/linktopicture1.jpg" class="someImage"></a></li>
  <li><a href=""><img src="/linktopicture2.jpg" class="someImage"></a></li>
  <li><a href=""><img src="/linktopicture3.jpg" class="someImage"></a></li>
</ul>

<div class="someDiv">
  <!-- those source links should be written here like this:
  /linktopicture1.jpg
  /linktopicture2.jpg
  /linktopicture3.jpg 
  -->
</div>

我尝试过类似的东西,但这不对:

的jQuery

$(document).ready(function() {
  $('.someList li').each(function() {
     var $this = $(this);

     // Get src attribute from img
     var url = $this.find('.someImage').first().attr('src');

     // Set href attribute on a
     $this.find('.someDiv').first().attr(url);
  });
});

1 个答案:

答案 0 :(得分:4)

问题出在声明中

 $this.find('.someDiv').first().attr(url);

.someDiv不是当前元素的子元素,即this,因此上面的代码将不起作用。

改为使用

$('.someDiv').append(url);

&#13;
&#13;
$(document).ready(function() {
  $('.someList li').each(function() {
    var $this = $(this);
    var url = $this.find('.someImage').attr('src');
    //Set anchor href
    $this.find('a').attr('href', url);
    $('.someDiv').append(url);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="someList">
  <li>
    <a href=""><img src="/linktopicture1.jpg" class="someImage"></a>
  </li>
  <li>
    <a href=""><img src="/linktopicture2.jpg" class="someImage"></a>
  </li>
  <li>
    <a href=""><img src="/linktopicture3.jpg" class="someImage"></a>
  </li>
</ul>

<div class="someDiv">
</div>
&#13;
&#13;
&#13;