![](/img/trans.png)
[英]How to read URL which stored in a data-src of a image and set that URL in src of another img controller onclick?
[英]How can I set the data-src on an img with pure JS?
我想在我用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上設置data-src?
如果要設置屬性 ,則應使用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';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.