如何通过HTML和JavaScript获取按钮或输入框的onclick绑定方法名
提取按钮绑定的JavaScript方法名
嘿,我来帮你搞定提取按钮上绑定的onclick方法名这件事,下面给你两种实用的方案:
方法一:逐个获取DOM元素解析
你可以直接定位到目标按钮,提取它的onclick属性值,再通过简单的字符串处理拿到方法名:
// 获取第一个<button>按钮 const button1 = document.querySelector('button[onclick]'); // 拿到onclick属性的内容 const onclickContent1 = button1.getAttribute('onclick'); // 去掉可能存在的括号,得到方法名 const methodName1 = onclickContent1.replace(/\(\)/g, ''); console.log(methodName1); // 输出:MyFunction // 获取第二个<input>类型的按钮 const button2 = document.querySelector('input[type="button"][onclick]'); const onclickContent2 = button2.getAttribute('onclick'); const methodName2 = onclickContent2.replace(/\(\)/g, ''); console.log(methodName2); // 输出:MyFunction2
方法二:正则表达式批量提取
如果页面上有多个需要处理的按钮,用正则表达式批量匹配会更高效:
// 假设你拿到了包含按钮的HTML片段 const targetHtml = ` <button onclick="MyFunction">Button 1</button> <input type="button" name="hola" value="hola" onclick="MyFunction2"> `; // 匹配onclick属性里的方法名(兼容带括号和不带括号的情况) const methodRegex = /onclick="([a-zA-Z0-9_]+)(\(\))?"/g; let matchResult; const allMethodNames = []; // 循环匹配所有符合条件的方法名 while ((matchResult = methodRegex.exec(targetHtml)) !== null) { allMethodNames.push(matchResult[1]); } console.log(allMethodNames); // 输出:["MyFunction", "MyFunction2"]
小提示
- 如果
onclick里有带参数的情况(比如onclick="MyFunc('hello')"),可以把正则调整为/onclick="([a-zA-Z0-9_]+)\(/,就能准确提取方法名了。 - 要是按钮的事件是通过
addEventListener绑定的,这种方法就不适用啦,因为这类绑定不会体现在HTML属性中。
内容的提问来源于stack exchange,提问作者Felipe Vallejo Orozco
相关产品推荐
相关产品推荐

