2015-04-15 52 views
1

我想要从任何元素获取img标签属性值,img标签可能会超过1个,也可以随机化。 一样,javascript - 如何从任何元素获取img标签?

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

我要抢他们的title属性值,然后希望在一些var currentHTML;存储与所有现有的div数据。

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

和输出的元素应该是这样的,

hellow :) how are u :D 

我怎样才能做到这一点?

在此先感谢。

+0

我不知道如何做到这一点?这就是为什么我问。 我认为如何做到这一点,我认为它需要一些循环。 – hsn0331

+0

您应该阅读[如何提出问题](http://stackoverflow.com/help/how-to-ask),其中解释说您应该在提问之前显示您尝试过的内容。 –

回答

4

试试这个:

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

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

UPDATE:

事情变得更加复杂。检查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> 

所以,你可以做一个以上的元素。我希望这有帮助。

+0

但这个小提琴没有像我想问的那样的输出,就像 hellow :)如果你添加console,你是怎样的:D – hsn0331

+0

。log(currentHTML);'或者提醒它,你会看到它正在返回标题标签 – Paul

+0

我知道,但是我怎样才能像这样使用它们,'hellow :)你怎么样:D'? – hsn0331

2

这是一个你可以重复使用的整洁的小函数。

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

 
});
<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>

+0

你也做得很好:) – hsn0331

+0

这个函数和方法有bug,如果多个imgs存在在每个时间旁边,然后更换方法不起作用正确,如 '' 和结果是,':) :)',而不是':):D' – hsn0331

+0

这个函式还追加'Replycancel'与结果 – hsn0331