I want to use the id name of the html element as the function name of the callback function.

Asked 1 years ago, Updated 1 years ago, 32 views

When specifying the function funcdog in the callback function, I would like to specify the part of dog using the id name of the html element button.Is this possible? If so, what are the possible ways to do you think so? If the function name is a string, you want to do the following:

const button= document.querySelector('button');
button.addEventListener('click', `func${button.id}()`); 
//<button type="button" id='dog'>dog</button>

javascript

2022-09-30 20:22

1 Answers

Generally, it's a bad way to do it's a bad way.If you dynamically rename a function when executing a program in the function call section, you will find it difficult to control errors when the generated function name does not exist, and you will find it difficult to define the function call relationship.Also, although not detailed, it may affect the program's execution speed in some cases.

Instead, consider whether the information Event passed to the argument can handle it.For example, if the callback is defined like function exampleFunction(event){...}, event.target.id in the function will tell you the caller ID.This allows you to check internally to see if the function is reasonable and produce the error you want.

これ How to proceed further depends on why the questioner wanted to do this. If you have more trouble using Event, try posting it as a new question, including the context of why you are in trouble.Note: XY Problem


2022-09-30 20:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.