如何使用 OnClick 事件调用 JS 函数 [英] How to Call a JS function using OnClick event

查看:53
本文介绍了如何使用 OnClick 事件调用 JS 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调用我在标题中添加的 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.  
    }
}

JSFiddle

这篇关于如何使用 OnClick 事件调用 JS 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆