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

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

问题描述

我试图调用我在标题中添加的JS函数。
请在下面的代码中找到我的问题场景。
注意:我无法访问我的应用程序中的正文。
每次我点击 id =Save元素时,它只会调用 f1(),但不会乐趣()。我怎么才能让它调用我的 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>


推荐答案

您正在试图附加一个事件侦听器函数元素被加载。在 onload 事件侦听器函数中放置 fun()。由于 onclick 属性将被忽略,因此在该函数中调用 f1()

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天全站免登陆