简体   繁体   English

使用Javascript动态更改html按钮的属性

[英]Dynamically change attribute of html button with Javascript

I have an html button where the 'data-item-price' attribute needs to be dynamically set on page load.我有一个 html 按钮,其中需要在页面加载时动态设置“data-item-price”属性。 The button has to be html but I can manipulate it with Javascript.该按钮必须是 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>
  • Using DOM's setAttribute() property使用 DOM 的setAttribute()属性

     const snipcart = document.querySelector('.snipcart-add-item') mydiv.setAttribute("data-item-price", 18)
  • Using JavaScript's dataset property使用 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