【问题标题】:Find img tag and replace with another tag查找 img 标签并替换为另一个标签
【发布时间】:2015-09-19 14:28:06
【问题描述】:

如何使用 jQuery 找到 img 标签并用 span 标签替换它?

<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>

【问题讨论】:

  • id="recommend" 应该是唯一的......
  • 我已经改进了代码块的格式,删除了不需要的感谢信,将问题的描述移到代码块上方,并改写了标题和内容。我还从标题中删除了库名称,因为由于标签的存在,它不是必需的。

标签: jquery image replace src


【解决方案1】:

您可以使用 jquery 的 replace()replaceWith() 方法来实现您正在尝试的。

以下是它们的用法链接:

https://api.jquery.com/category/manipulation/dom-replacement/

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

【讨论】:

  • jsfiddle.net 这是提供相同解决方案的小提琴。是的,您不能对两个段落标签都使用健全的 id 推荐。
【解决方案2】:
<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/

【讨论】:

    【解决方案3】:

    正如其他人所说,ID 应该是唯一的。相反,您可以为多个共享相同类名的元素使用类。这里我举一个例子来实现这一点:

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

    如果要将图片替换为span的内容,请添加.html()

    DEMO - 检查元素以查看替换内容。

    【讨论】:

      猜你喜欢
      • 2014-07-09
      • 2011-10-28
      • 2013-11-23
      • 2013-05-26
      • 1970-01-01
      • 2015-06-24
      • 2012-11-26
      • 1970-01-01
      相关资源
      最近更新 更多