我想在我用 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 说:必须是左值
所以我不能分配它。
我还能如何从纯 JavaScript(没有 jQuery)在 img 上设置数据源?
最佳答案
如果你想设置一个属性,你应该使用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';
关于javascript - 如何使用纯 JS 在 img 上设置数据源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51734707/