我想在我用JS创建的img上设置一个data-src属性。
为什么这不起作用?
const image = document.createElement('img');
image.className = 'restaurant-img';
image.src = '/img/1.jpg';
image.data-src = DBHelper.imageUrlForRestaurant(restaurant);
li.append(image);
IDE表示:必须为左值
所以我不能分配它。
否则我如何在img上设置data-src,然后从纯JavaScript (无jQuery)设置;
发布于 2018-08-08 04:15:07
如果要设置属性,则应使用setAttribute
。
如下所示:
const image = document.createElement('img');
image.className = 'restaurant-img';
image.src = '/img/1.jpg';
image.setAttribute('data-src', 'foobar');
document.body.appendChild(image);
console.log(image.outerHTML);
如果要设置元素的属性名称data-src
,则必须使用方括号表示法,因为-
在点表示法中是非法字符:
image['data-src'] = 'foobar';
https://stackoverflow.com/questions/51734707
复制相似问题