2015-07-02 100 views
0

我如何才能找到img標籤,並使用jQuery替換爲span標籤?查找img標籤並用另一個標籤替換

<style> 
    .box{ 
     display:inline-block; 
     width:100px; 
     height:20px; 
     line-height:20px; 
     font-size:11px; 
    } 
</style> 

<p id="recommend"> 
    <img src="search.gif" alt="find"> <!-- find this img tag without id and class--> 
</p> 

<!-- next --> 

<p id="recommend"> 
    <span class="box">search</span><!-- replace this --> 
</p> 
+2

'ID =「建議」'應該是唯一.... –

+0

我具有改進的代碼塊,除去由於筆記的格式由於不需要它,移動的問題的描述是代碼塊的上方和重新標題和內容。由於存在標籤,我也從標題中刪除了庫名稱,因爲它不是必需的。 – Harry

回答

0
<style> 
.box{display:inline-block;width:100px;height:20px;line-height:20px;font-size:11px;} 
</style> 

<p id="recommend"> 
    <img src="search.gif" class="find"> <!-- find this img tag without id and class--> 
</p> 

<script type="text/javascript"> 
$(document).ready(function() { 
    $('<span class="box">search</span>').replaceAll('img.find'); 
    // OR... 
    $('img.find').replaceWith('<span class="box">search</span>'); 
}); 
</script> 

https://api.jquery.com/replaceAll/

http://api.jquery.com/replacewith/

0

正如有人說,ID應b獨特。相反,您可以使用class爲多個元素共享相同的類名稱。在這裏,我舉個例子來實現這一目標:

的Html

<p class="recommend"> 
    <img src="search.gif" alt="find" /> 
    <!-- find this img tag without id and class--> 
</p> 
<!-- next --> 
<p class="recommend"> 
<span class="box">search</span> 
<!-- replace this --> 
</p> 

jQuery的

$('.recommend').first().find('img').remove().end().html(function(){ 
    return $(this).siblings().find('span.box'); 
}); 

$('img').replaceWith(function(){ 
return $(this).parent().next().find('span.box'); 
}); 

添加.html()如果要更換圖像與跨度的內容。

DEMO - 檢查元素以查看替換內容。

相關問題