Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从<;中删除所有属性;车身>;使用js或jquery_Javascript_Jquery_Attributes - Fatal编程技术网

Javascript 如何从<;中删除所有属性;车身>;使用js或jquery

Javascript 如何从<;中删除所有属性;车身>;使用js或jquery,javascript,jquery,attributes,Javascript,Jquery,Attributes,如何使用js或jquery从中删除所有属性。 (我不知道主体中的属性是什么,我想删除所有属性)您可以使用DOM Level 1 Coreattributes属性作为列表访问属性。作为普通JS: function removeAllAttrs(element) { for (var i= element.attributes.length; i-->0;) element.removeAttributeNode(element.attributes[i]); } re

如何使用js或jquery从中删除所有属性。
(我不知道主体中的属性是什么,我想删除所有属性)

您可以使用DOM Level 1 Core
attributes
属性作为列表访问属性。作为普通JS:

function removeAllAttrs(element) {
    for (var i= element.attributes.length; i-->0;)
        element.removeAttributeNode(element.attributes[i]);
}
removeAllAttrs(document.body);
或者穿着jQuery插件的衣服:

$.fn.removeAllAttrs= function() {
    return this.each(function() {
        $.each(this.attributes, function() {
            this.ownerElement.removeAttributeNode(this);
        });
    });
};

$('body').removeAllAttrs();
var$newBody=$('');
$newBody.append($('body').contents());
$('body')。替换为($newBody);

像这样的方法可能行得通。

我不知道这是不是最好的方法,但它行得通

$('body').each(function(){
     var $body = $(this);
     var attributes = $.makeArray(this.attributes);

     $.each(attributes, function(indexInArray, valueOfElement) {
         $body.removeAttr(valueOfElement.name);
     });
});

假设要删除
元素的属性,可以使用

$(element).removeAttr($.makeArray(element.attributes)
                       .map(function(item){ return item.name;})
                       .join(' '));
请注意,这仅适用于自ES2015起的jQuery 1.7+

,您可以使用


这样做的最终目标是什么?@meder:我只能假设他无法控制他所控制的页面的输出。有点相关@meder-虽然最终目标根本不重要,但我的最终目标是复杂的PJAX处理。原因不计其数。替换
主体
会丢失指向它的任何JavaScript/jQuery引用,包括其中的任何事件处理程序。onclick等都是XHTML视图中的属性。此外,确保它在任何其他jQuery事件绑定之前运行是很简单的。这就是我需要的。非常感谢。这在IE中有效吗?在IE
attributes
中,包含所有可能的属性名称,无论它们是否已设置,我想知道这是否会导致问题。尚未对其进行测试。对
属性的类似数组的访问
似乎确实有效,与属性名称访问的问题无关。您可以扩展jQuery现有的
.removeAttr()
方法,使其接受零参数以从每个元素中删除所有属性,而不是创建新的
$.fn.removeAllAttrs
“每个”在这里真的有必要吗?
$(element).removeAttr($.makeArray(element.attributes)
                       .map(function(item){ return item.name;})
                       .join(' '));
const el = document.body;
const attributes = Array.from(el.attributes);
attributes.forEach(attr => el.removeAttributeNode(attr));