如何使用 OnClick 事件调用 JS 函数 [英] How to Call a JS function using OnClick event
问题描述
我正在尝试调用我在标题中添加的 JS 函数.请找到以下显示我的问题场景的代码.注意:我无权访问我的应用程序中的正文.每次我点击带有 id="Save"
的元素时,它只会调用 f1()
而不是 fun()
.我怎样才能让它甚至调用我的 fun()
?请帮忙.
I am trying to call my JS function that I added in the header.
Please find below code that shows my problem scenario.
Note: I don't have access to the body in my application.
Everytime I click on the element with id="Save"
it only calls f1()
but not fun()
. How can I make it call even my fun()
?
Please help.
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("Save").onclick = function fun()
{
alert("hello");
//validation code to see State field is mandatory.
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
State:
<select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
</form>
<table><tr><td id="Save" onclick="f1()">click</td></tr></table>
</body>
</html>
推荐答案
您正试图在加载元素之前附加一个事件侦听器函数.将 fun()
放在 onload
事件侦听器函数中.在此函数中调用 f1()
,因为 onclick
属性将被忽略.
You are attempting to attach an event listener function before the element is loaded. Place fun()
inside an onload
event listener function. Call f1()
within this function, as the onclick
attribute will be ignored.
function f1() {
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
}
window.onload = function() {
document.getElementById("Save").onclick = function fun() {
alert("hello");
f1();
//validation code to see State field is mandatory.
}
}
这篇关于如何使用 OnClick 事件调用 JS 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!