2016-07-26 111 views
0

我有這樣的代碼如何動態更新HTML屬性

<div class="g-popupgrid-item g-zoom" data-size="395x385"> 

我想與圖像大小動態填充395x385。

我有一個JS函數獲取圖像大小,我不知道如何打印/回聲/ document.write它在HTML標記。

+4

您將不打印/ echo/document.write。你在jQuery中使用DOM和'.setAttribute()'。 ('data-size',var_with_value_you_want)' –

+1

當然,你可以在沒有jQuery的情況下做到這一點:document.querySelector(「g -popupgrid-item g-zoom「)。setAttribute(」data-size「,your_value_here); – SimianAngel

回答

2

我會避免使用jQuery這麼簡單的任務,除非您已經在您的項目中使用它。普通的JavaScript:

var div = document.querySelector('.g-popupgrid-item'); 
var newSize = '100x100'; // for example 
div.setAttribue('data-size', newSize); 
+0

或在兼容的瀏覽器中使用[dataset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset)'div.dataset.size = newSize' –

+0

我已經在使用數據集其實:) – Eoin

2

獲取Node使用JavaScript,然後對其進行修改以滿足您的需求:

var container = document.querySelector(".g-popupgrid-item .g-zoom") 
container.setAttribute("data-size", value) 

請記住,這將只使用這些類影響的第一要素,如果你想影響他們總之,使用下面的代碼:

var containers = document.querySelectorAll(".g-popupgrid-item .g-zoom") 
containers.forEach(function(container) { 
    container.setAttribute("data-size", value) 
}) 

而且記住,containers不是Array這是一個NodeList。更多here

編輯:根據@Eoin,在Firefox不支持NodeList S上的.forEach()方法。您也可以使用標準的for循環代替它:

var containers = document.querySelectorAll(".g-popupgrid-item .g-zoom") 
for (var i = 0; i < containers.length; i++) { 
    containers[i].setAttribute("data-size", value) 
} 
+1

你指出了返回一個'NodeList'而不是'getElementsByClassName'生成的'HTMLCollection'的一個很好的特性 - 'forEach'方法。你不需要重組爲一個數組。 – Damon

+1

@Damon我剛剛讀了一大堆關於'NodeList'和'HTMLCollection'之間的區別,因爲這是我真的不瞭解瀏覽器js的一件事。在@Eoin的部分良好的時機,雖然 – MayorMonty

+0

我試圖實現它,但現在我得到一個錯誤 '類型錯誤:containers.forEach不是function' 這裏是我完整的代碼 – Eoin