当动作url = "https://someurl/somepath"“时,我想注入一个带有函数的onsubmit事件,该函数将以下面的形式动态调用。如何在javascript中实现?
注意:可能有一些表单没有类的实例。
<form action="https://someurl/somepath" method="GET" class="someclass">
</form>发布于 2021-03-26 16:34:17
你可以这样做:
var form = document.querySelector("form")[0];
if(form.action == "https://someurl/somepath"){
form.addEventListener("submit", myfunction);
}发布于 2021-03-26 16:41:20
您可以创建一个数组,其中包含要允许提交的URL。
const form = document.querySelector('.someclass');
const url = form.action;
const URLs = [
'https://someurl/somepath',
'https://someOtherurl/someOtherpath',
];
if (URLs.includes(url)) form.addEventListener("submit", func);您还可以按操作选择表单:
const url = 'https://someurl/somepath';
const form = document.querySelector(`form[action='${url}']`);
form.addEventListener("submit", func);发布于 2021-03-26 17:26:36
检查操作,如果不允许使用event.preventDefault,则停止提交。代码段使用event delegation
document.addEventListener("submit", handle);
function handle(evt) {
if (evt.type === "submit") {
if (evt.target.action.endsWith("somepath")) {
evt.preventDefault(); // demo, remove for real use
return console.log("allowed");
}
evt.preventDefault();
console.log("not allowed");
return false;
}
}form {
margin-bottom: 1rem;
}<form action="https://someurl/somepath" method="GET" class="someclass">
<input type="submit"/>
</form>
<form action="https://someurl/otherpath" method="GET" class="someclass">
<input type="submit"/>
</form>
<form action="https://someurl/yeatanotherpath" method="GET" class="someclass">
<input type="submit"/>
</form>
https://stackoverflow.com/questions/66813363
复制相似问题