【问题标题】:jQuery replace matched element with another element tagjQuery用另一个元素标签替换匹配的元素
【发布时间】:2013-04-30 22:38:23
【问题描述】:

我将我的特色图片包装在一个图形元素中。但是,IE8 无法正确识别图形元素并破坏了我的图像。所以,我正在尝试使用 jQuery 来检测 IE8 并用一个简单的 div 元素替换 figure 元素。

这是我的测试 jQuery:

jQuery('.entry figure.figureFeatured').replaceWith(
    jQuery('<div/>').html(
        jQuery('.entry figure.figureFeatured').html()
        )
    );

它工作正常,只是原始图形元素的属性不再附加到替换的 div 元素(根据 chrome 的检查器)

【问题讨论】:

    标签: jquery replacewith


    【解决方案1】:

    也可以使用下面的代码来复制属性...

    jQuery('.entry figure.figureFeatured').replaceWith(
        var $div=jQuery('<div/>');
        $div.html( jQuery('.entry figure.figureFeatured').html() )
         $div.attr(jQuery('.entry figure.figureFeatured').getAttributes());
        );
    

    您需要将 getAttributes 函数添加到 Jquery,如下所示

    (function($) {
        $.fn.getAttributes = function() {
            var attributes = {}; 
    
            if( this.length ) {
                $.each( this[0].attributes, function( index, attr ) {
                    attributes[ attr.name ] = attr.value;
                } ); 
            }
    
            return attributes;
        };
    })(jQuery);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 2011-11-29
      • 1970-01-01
      • 2017-12-22
      相关资源
      最近更新 更多