簡體   English   中英

使用Javascript動態更改html按鈕的屬性

[英]Dynamically change attribute of html button with Javascript

我有一個 html 按鈕,其中需要在頁面加載時動態設置“data-item-price”屬性。 該按鈕必須是 html,但我可以使用 Javascript 操作它。

<button class="snipcart-add-item"
  data-item-id="Job123"
  data-item-price= 18 *a dynamically passed number*
  data-item-url= "www.abc.co/priceevaluation"
 data-item-name="Validate">
  Add to cart
</button>
  • 使用 DOM 的setAttribute()屬性

     const snipcart = document.querySelector('.snipcart-add-item') mydiv.setAttribute("data-item-price", 18)
  • 使用 JavaScript 的dataset屬性

     const snipcart = document.querySelector('.snipcart-add-item') snipcart.dataset['item-price'] = 18 //or use camelCase turn into kabeb-case snipcart.itemPrice = 18

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM