admin管理员组文章数量:1401643
I have an input field that looks like this:
<input placeholder="Card Number" name="cc-number" data-stripe="number" class="add-card-form__card-number input" value="">
I'd like to do something like this:
onFocus (e) {
const { 'data-stripe': name, value } = e.target
// do something with `name` and `value`
}
I know I can use e.target.getAttribute('data-stripe')
, but that defeats the purpose of destructuring. Any ideas how to do this?
Here it says exactly what I'm doing. How to destructure object properties with key names that are invalid variable names?
I have an input field that looks like this:
<input placeholder="Card Number" name="cc-number" data-stripe="number" class="add-card-form__card-number input" value="">
I'd like to do something like this:
onFocus (e) {
const { 'data-stripe': name, value } = e.target
// do something with `name` and `value`
}
I know I can use e.target.getAttribute('data-stripe')
, but that defeats the purpose of destructuring. Any ideas how to do this?
Here it says exactly what I'm doing. How to destructure object properties with key names that are invalid variable names?
Share Improve this question edited Aug 29, 2021 at 8:44 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Sep 9, 2016 at 22:30 Alex CoryAlex Cory 11.9k11 gold badges57 silver badges65 bronze badges2 Answers
Reset to default 5There's no data-stripe
property in the DOM element. All data-XXX
attributes are turned into properties of the dataset
property. So you should use:
onFocus(e) {
const { dataset: { stripe: name }, value } = e.target;
// do something with name and value
}
It can also be accessed as an element of the attributes
property, but since this is an array and the order is unpredictable, it's not useful for destructuring.
This is not a hyphen issue, you are just not calling HTML DOM correctly. Even if your custom attribute was "stuff" you cannot access it as e.target.stuff. Your own link shows how to access hyphenated: attributes.
var {"data-stripe":{value:myVariableName}} = e.target.attributes;
//myVariableName="number"
本文标签: javascriptHow to destructure etarget when hyphens are in the attributeStack Overflow
版权声明:本文标题:javascript - How to destructure e.target when hyphens are in the attribute? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744312408a2600094.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论