如何使用jquery一次删除属性
$('#myImage').removeAttr('class').removeAttr('style').removeAttr('border') 这一个很好,但是有没有办法从元素中删除一组属性 我把代码改了一点,比如如何使用jquery一次删除属性,jquery,Jquery,$('#myImage').removeAttr('class').removeAttr('style').removeAttr('border') 这一个很好,但是有没有办法从元素中删除一组属性 我把代码改了一点,比如 $.fn.removeAttrs = function () { // Convert all passed arguments to an array var args = arguments[0].split(' '), attr;
$.fn.removeAttrs = function () {
// Convert all passed arguments to an array
var args = arguments[0].split(' '),
attr;
// Loop, removing the first array item on each iteration
while (attr = args.shift())
this.removeAttr(attr);
// Return the jQuery object for chaining
return this;
}
像下面这样称呼它
$('#myImage').removeAttrs('class style border');
不,但你可以很容易地写下自己的:
$.fn.removeAttrs = function () {
// Convert all passed arguments to an array
var args = Array.prototype.slice.call(arguments),
attr;
// Loop, removing the first array item on each iteration
while (attr = args.shift())
this.removeAttr(attr);
// Return the jQuery object for chaining
return this;
}
$('#myImage').removeAttrs('class', 'style', 'border');
下面是一个带有几个不同重载的jQuery样式:
$.fn.removeAttrs = function () {
// Convert all passed arguments to an array
var args = Array.prototype.slice.call(arguments),
attr;
// Handle passing arrays or space-separated strings
if (args.length == 1)
args = $.isArray(args[0]) ? args[0] : args[0].split(" ");
// Loop, removing the first array item on each iteration
while (attr = args.shift())
this.removeAttr(attr);
// Return the jQuery object for chaining
return this;
}
// Now all of the following will work
$('#myImage').removeAttrs(['class', 'style', 'border']);
$('#myImage').removeAttrs('class', 'style', 'border');
$('#myImage').removeAttrs('class style border');
我写了这个,太高兴了
// classNames is an array of attribute names you want to remove from the element.
// jQueryElement is the jQuery element to remove the attributes from.
function removeSetOfAttributesFromAnElement(attNames, jQueryElement) {
$.each(attNames, function() {
jQueryElement.removeAttr(this);
}
}
// call it!
removeSetOfAttributesFromAnElement(['class','style','border'], $("#myImage"));
不直接。
第一个问题是你真的想这么做吗。请记住,您将失去Id属性
但是如果您必须这样做,那么您可以真正创建一个与源标记(DIV等)相同的新标记,然后使用$('#target').html($('#source').html())获取源html jquery中已经有一个函数了
jQuery(element).removeAttr('attribute1 attribuite2 attribute3');
将一次性删除所有属性
在这里,removeAttr可以使用一个列表
演示:即使对于开发人员控制台中的这个stackoverflow页面,您也可以这样做
jQuery('div#footer').removeAttr('id class'))
这将从div中删除属性id和class可能重复的@RPM1984:这不完全相同;这个问题要求删除一些属性,而不是所有属性,因此答案将完全不同。是的-我本来打算发布一个答案,但我认为Q@cletus的答案很好,并且只需要为OP添加一行代码(通过属性列表删除)。对于误解问题,我深表歉意。我的方法会去掉标签的所有属性。很好,我可以这样称呼它吗$(“#myImage”).removeSetOfAttributesFromAnElement(['class','style','border'])@Naresh,您可能可以使用
$连接链接功能。fn
Andy指出的名称空间。哇!这太酷了。。我只是做了同样的事情,比如将attr作为空格分隔字符串传递。。获取错误TheRetcha,我只需要拆分传递参数的第一个索引:)@Naresh:有一个小错误(调用splice
而不是slice
来转换参数)-我现在已经更新了:-)