2015-04-15 51 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