元素属性中html属性怎么改,JavaScript 无法修改 html 元素的属性是怎么回事?

js 對新手最不友好的地方在於沒有在可能出現與預期不符的行爲時報錯(貌似只有靜態語言能做到這一點哎)。

當然這樣的特性對入門之後是很友好的。。。

Returns an array-like object of all child elements which have all of

the given class names. When called on the document object, the

complete document is searched, including the root node. You may also

call getElementsByClassName() on any element; it will return only

elements which are descendants of the specified root element with the

given class names.

var elements = document.getElementsByClassName(names);

elements is a live HTMLCollection of found elements.

HTMLCollection 是一個 array-like object 而不是 array,也不是 element,所以既沒有 array 的方法也沒有 element 的方法、屬性

因此我們從 Array 原型獲取所需的方法並調用。

Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(x){ x.attribute = newValue });

當然你可以修改 HTMLCollection 原型實現快捷方式:

HTMLCollection.prototype.setAttr = function(name, value) {

Array.prototype.forEach.call(this, function(x){ x[name] = value; });

};

document.getElementsByClassName("classname").setAttr('attribute', newValue);

bVlDDa

也可以採用現成的封裝比如 jQuery。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值