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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

There'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