前端 - JavaScript 无法修改 html 元素的属性是怎么回事?
巴扎黑
巴扎黑 2017-04-10 15:11:10
0
6
442

rt,检查了好久,也没能找到原因。。。
这些代码的目的是先获得新的url值,然后替换掉原来的image元素的src属性为新的url值,通过这个来达到变更图片的目的。。。
然而一直试都是没能改过来。。。
按理来说:
document.getElementsByClassName("classname").attribute = newValue;
不是可以修改类名为"classname"的元素的属性么?
求助,万分感谢!!!

巴扎黑
巴扎黑

reply all(6)
迷茫
document.getElementsByClassName("classname")[0].src = url;
大家讲道理

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.

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsB...

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);

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

洪涛

楼主获取的是一个集合,而不是单个img元素。可以根据索引获取到单个元素后修改对应属性

Ty80

别用原生DOM API去搞了,换JQuery上吧:

$('.avatar').attr('src', url_avatar);

多简洁

参考:JQuery教程 - w3cschool

Peter_Zhu

公子正解
document.getElementsByClassName("classname") 返回的是一个对象数组(注意这里是Elements),
所以document.getElementsByClassName("classname")[0] 数组的第一个才是你要的DOM元素,
也可以用document.querySelector('.classname').src = url

左手右手慢动作

建议你用jQuery吧,直接用JavaScript有些蛋疼,而且你还得考虑浏览器的兼容性

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template