javascript - 如何从任何元素获取img标签?

时间:2015-04-15 10:41:15

标签: javascript jquery html

我想从任何元素获取img标签属性值,img标签可以超过1,也可以随机化。 等,

<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>

我想获取他们的title属性值,然后想要将所有现有div数据存储在一些var currentHTML;中。

然后插入任何元素,就像$('#div').html(currentHTML);

一样

并且输出应该是这样的,

 hellow :) how are u :D

我该怎么做?

提前致谢。

2 个答案:

答案 0 :(得分:4)

试试这个:

$("img").each(function()
{
    $(this).replaceWith($(this).prop("title"));
});

Fiddle。它只是循环遍历每个图像,并用自己的title属性替换它(replaceWith()}。

更新:

事情变得更加复杂。检查this snippet

// The text result you want
var currentHTML = "";

// Instead of search for each image, we can search of elements that 
// contains images and you want to get their text
$(".images").each(function()
{
    // Check note #1
    var cloned = $(this).clone().css("display", "none").appendTo($("body"));

    // Here we select all images from the cloned element to what 
    // we did before: replace them with their own titles
    cloned.find("img").each(function()
    {
        $(this).replaceWith($(this).prop("title"));
    });

    // Add the result to the global result text
    currentHTML+= cloned.html();
});

// After all, just set the result to the desired element's html
$("#div").html(currentHTML);

注意#1:以下是该行中发生的事情:

请注意,在您的初始html中,包含图片的div收到了课程images

<div class="images"> hellow <img src='icons/smile.png' title=':)' /> how are u <img src='icons/smile2.png' title=':D' /></div>

所以你可以在多个元素上做到这一点。我希望这会有所帮助。

答案 1 :(得分:2)

这是一个可以重复使用的简洁小功能。

&#13;
&#13;
$(function(){

  function getImageReplace($el) {
    var $copy = $el.clone();
    $copy.find('img').each(function(){
      $(this).replaceWith($(this).attr('title'));
    });
    return $copy.text();
  }

  //now you can use this on any div element you like
  $('#go').click(function() {
    alert(getImageReplace($('div')));
  });

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>   
<button id='go'>Convert images</button>
&#13;
&#13;
&#13;

相关问题