【发布时间】:2018-02-13 12:52:03
【问题描述】:
我有 3 个不同的 HTML 页面,其中包含一个表单。
除了 id 属性(和一些子 id 属性)之外,所有表单看起来都相同,尽管每个表单的 Javascript 行为应该相同。
我想在某个操作上调用相同的 Javascript 函数,但必须确定从哪个表单触发了该操作,以便该函数知道应该执行其主体的哪个部分。
form1.html
<form id="form1">
<input id="fname1"/>
<input type="submit" id="btn-sub" onclick="fun()"/>
<p id="demo"></p>
</form>
form2.html
<form id="form2">
<input id="fname2"/>
<input type="submit" id="btn-sub" onclick="fun()"/>
<p id="demo"></p>
</form>
form3.html
<form id="form3">
<input id="fname3"/>
<input type="submit" id="btn-sub" onclick="fun()"/>
<p id="demo"></p>
</form>
javascript函数
function fun() {
// Here I would like conditions to look like
if ( /* function call from form1 id then */ ) {
document.getElementById("demo").innerHTML = "Hello form 1";
}
if ( /* function call from form2 id then */) {
document.getElementById("demo").innerHTML = "Hello form 2";
}
if ( /* function call from form3 id then */) {
document.getElementById("demo").innerHTML = "Hello form 3";
}
}
【问题讨论】:
-
您可以将不同的参数传递给 fun() 并在此基础上为 if...添加条件...
-
如何将当前表单 ID 作为参数发送给 javascript 函数
-
格式化,改写。
标签: javascript html