是否有一个jQuery插件的outerHTML

Is there a jQuery plugin for outerHTML?

本文关键字:outerHTML 插件 jQuery 有一个 是否      更新时间:2023-09-26

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

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

看起来你只是想在每个.t周围包装一个<a>元素。jQuery已经有一个方法来做这个叫做.wrap

您可以在https://api.jquery.com/wrap/

阅读文档

这个问题的一个用法示例是:

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



如果你认为你真的需要设置一个元素的outerHTML,你可能想尝试使用我昨天写的代码片段作为另一个问题的答案。它模仿.html()的行为,但允许您获取或设置outerHTML()

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字符串。

创建简单的outerHTML jQuery插件:

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

// usage
$("<p>Hello</p>").outerHTML(); //  "<p>Hello</p>"

您可以使用this在您的每个!

this.outerHTML

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

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

一个新的jQuery outerHTML插件版本在https://github.com/darlesson/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>");
    });