简体   繁体   English

如何使用 OnClick 事件调用 JS 函数

[英]How to Call a JS function using OnClick event

I am trying to call my JS function that I added in the header.我正在尝试调用我在标题中添加的 JS 函数。 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() .每次我点击带有id="Save"的元素时,它只调用f1()而不是fun() How can I make it call even my fun() ?我怎样才能让它甚至叫我的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>

You are attempting to attach an event listener function before the element is loaded.您正在尝试在加载元素之前附加事件侦听器函数。 Place fun() inside an onload event listener function.fun()放在onload事件侦听器函数中。 Call f1() within this function, as the onclick attribute will be ignored.在此函数中调用f1() ,因为onclick属性将被忽略。

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 JSFiddle

You could use addEventListener to add as many listeners as you want.您可以使用 addEventListener 添加任意数量的监听器。

  document.getElementById("Save").addEventListener('click',function ()
    {
     alert("hello");
     //validation code to see State field is mandatory.  
    }  ); 

Also add script tag after the element to make sure Save element is loaded at the time when script runs还要在元素后添加script标签,以确保在脚本运行时加载Save元素

Rather than moving script tag you could call it when dom is loaded.您可以在加载 dom 时调用它,而不是移动脚本标记。 Then you should place your code inside the然后你应该把你的代码放在

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("Save").addEventListener('click',function ()
    {
     alert("hello");
     //validation code to see State field is mandatory.  
    }  ); 
});

example例子

I removed your document.getElementById("Save").onclick = before your functions, because it's an event already being called on your button.我在你的函数之前删除了你的document.getElementById("Save").onclick = ,因为它是一个已经在你的按钮上被调用的事件。 I also had to call the two functions separately by the onclick event.我还必须通过 onclick 事件分别调用这两个函数。

     <!DOCTYPE html>
      <html>
      <head>
      <script>
       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(); fun();">click</td></tr></table>

   </body>
   </html>

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head> .使用onclick属性或将函数应用于您的 JS onclick属性将删除<head> onclick初始化。

What you need to do is add click events on your button.您需要做的是在按钮上添加点击事件。 To do that you'll need the addEventListener or attachEvent (IE) method.为此,您需要使用addEventListenerattachEvent (IE) 方法。

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        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>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

Inline code takes higher precedence than the other ones.内联代码比其他代码具有更高的优先级。 To call your other function func () call it from the f1 ().要调用你的另一个函数 func() 从 f1() 调用它。

Inside your function, add a line,在您的函数中,添加一行,

function fun () {
// Your code here
}

function f1()
    {
       alert("f1 called");
       //form validation that recalls the page showing with supplied inputs.    

fun ();

    }

Rewriting your whole code,重写你的整个代码,

 <!DOCTYPE html>
    <html>
      <head>

      <script>

       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.   
           fun (); 
        }

      </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>

You can also do this with an anonymous javascript function by using a iife .您也可以使用iife使用匿名 javascript 函数执行此操作 Please note that this is considered a bad practice , though there are those rare times when there is no other option.请注意,这被认为是一种不好的做法,尽管在极少数情况下别无选择。

...
<span onclick="(function() { // function code here })())">click me!</span>
...

I agree with @George.我同意@George。 If we are to add or bind a event listener to an HTML element via JavaScript, we need to do once the DOM has been loaded.如果我们要通过 JavaScript 添加或绑定事件侦听器到 HTML 元素,我们需要在加载 DOM 后执行此操作。 For this we can use the window.onload() function in JavaScript.为此,我们可以使用 JavaScript 中的window.onload()函数。

<script>
   window.onload = function() {
      document.getElementById("Save").onclick = function fun() {
        alert("hello");
      }   
   }
</script>

Another way is to use the onclick event handler in the HTML as in the following code:另一种方法是在 HTML 中使用onclick事件处理程序,如以下代码所示:

<div onclick="myFunction()"></div>
<script>
   function myFunction() {
      alert("Hello");
   }
</script>

Note: It is NOT recommended to use both the approaches together.注意:不建议同时使用这两种方法。 As it will cause two functions to be called in a single click.因为它会导致在一次单击中调用两个函数。 Which is irksome.这很烦人。

function validate() {

    if( document.myForm.phonenumber.value == "" ) {
        alert( "Please provide your phonenumber!" );
        phonenumber.focus;
        return false;
    }
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.email.value))  {  
        return (true)  
    }  
    alert("You have entered an invalid email address!");
    return (false);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM