【问题标题】:Is there a jQuery plugin for outerHTML?是否有用于 outerHTML 的 jQuery 插件?
【发布时间】:2011-09-07 15:02:09
【问题描述】:

我想用相同的类名覆盖几个链接的outerHTML。我只是想知道这是否不起作用,因为 jQuery 不支持.outerHTML。如果有,可以参考一下吗?另外,有没有办法使这项工作:

$('.t').each(function() {
    $('.t').outerHTML = '<a href="http://www.google.com">' + 
        '<img src="' + $('.t').attr('src') + '" class="' + $('.t').attr('class') + '" /></a>';
});

【问题讨论】:

标签: javascript jquery


【解决方案1】:

看起来您只是想在每个 .t 周围包装一个 &lt;a&gt; 元素。 jQuery 已经有一个方法可以做到这一点,叫做.wrap

您可以在https://api.jquery.com/wrap/阅读文档

您的问题的用法示例是:

$('.t').wrap('<a href="http://google.com">');



如果你认为你真的需要设置一个元素的outerHTML,你可能想尝试使用我昨天写的sn-p 作为answer to another question。它模仿.html() 的行为,但允许您获取或设置outerHTML()

【讨论】:

    【解决方案2】:

    jQuery 提供你想要的,而不是作为一个完整的 'outerHTML' 函数:

    $('.t').each( function() {
        // Modify the html directly
        $(this).html('<img src="' + $('.t').attr('src') + '" class="' + $('.t').attr('class') + '" /></a>');
        // Use attr to change href
        $(this).attr('href','http://www.google.com');
    });
    

    你也可以 .append() 一个新的 $('') ,你已经用 .attr() 和 .addClass() 操作了它,而不是写出 html 字符串。

    【讨论】:

      【解决方案3】:

      创建简单的 outerHTML jQuery 插件:

      (function($) {
        $.fn.outerHTML = function() {
          return $(this).clone().wrap('<div></div>').parent().html();
        }
      })(jQuery);
      
      
      // usage
      $("<p>Hello</p>").outerHTML(); //  "<p>Hello</p>"
      

      【讨论】:

        【解决方案4】:

        您可以在每个人中使用this

        this.outerHTML
        

        要跨浏览器使用这个 jQuery 插件:

        https://github.com/darlesson/jquery-outerhtml

        【讨论】:

        【解决方案5】:

        https://github.com/darlesson/jquery-outerhtml 发布了一个新的 jQuery outerHTML 插件版本,它似乎可以满足您的需求:

            $(".t").each(function(){
        
                var $this = $(this),
                    // Get the attribute values
                    src = $this.attr("src"),
                    className = $this.attr("class");
        
                $this.outerHTML("<a href='http://www.google.com'><img src='" + src + "' class='" + className + "' /></a>");
        
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-05-11
          • 2011-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-23
          相关资源
          最近更新 更多