2015-07-02 101 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 - 检查元素以查看替换内容。

相关问题