【问题标题】:How to Call a JS function using OnClick event如何使用 OnClick 事件调用 JS 函数
【发布时间】:2014-02-24 00:12:45
【问题描述】:

我正在尝试调用我在标题中添加的 JS 函数。 请在下面找到显示我的问题场景的代码。 注意:我无权访问我的应用程序中的正文。 每次我单击带有id="Save" 的元素时,它只调用f1() 而不是fun()。我怎样才能让它呼叫我的fun()? 请帮忙。

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

【问题讨论】:

标签: javascript html forms validation html-validation


【解决方案1】:

我同意@George。如果我们要通过 JavaScript 添加或绑定事件监听器到 HTML 元素,我们需要在 DOM 加载后执行。为此,我们可以在 JavaScript 中使用 window.onload() 函数。

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

另一种方法是在 HTML 中使用 onclick 事件处理程序,如下代码所示:

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

注意:不建议同时使用这两种方法。因为它会导致一次单击调用两个函数。这很烦人。

【讨论】:

    【解决方案2】:

    您也可以使用iife 使用匿名javascript 函数来执行此操作。 请注意,这被认为是一种不好的做法,尽管在​​极少数情况下没有其他选择。

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

    【讨论】:

      【解决方案3】:

      使用onclick 属性或将函数应用于您的JS onclick 属性将删除您在&lt;head&gt; 中的onclick 初始化。

      您需要做的是添加按钮上的点击事件。为此,您需要 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>
      

      【讨论】:

        【解决方案4】:

        我在你的函数之前删除了你的document.getElementById("Save").onclick =,因为它是一个已经在你的按钮上调用的事件。我还必须通过 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>
        

        【讨论】:

          【解决方案5】:

          您正试图在加载元素之前附加事件侦听器函数。将 fun() 放在 onload 事件侦听器函数中。在此函数中调用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

          【讨论】:

          • 我无权访问正文中的代码。我的应用程序与上面的代码不同。无论如何现在,即使按照您的建议,它也只调用 fun() 而不是 f1()。
          • @VineethVarma 然后请发布您使用过的代码。
          • @VineethVarma 已编辑。
          【解决方案6】:

          您可以使用 addEventListener 添加任意数量的侦听器。

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

          还要在元素后添加script 标记,以确保在脚本运行时加载Save 元素

          您可以在加载 dom 时调用它,而不是移动脚本标签。然后你应该把你的代码放在

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

          example

          【讨论】:

            【解决方案7】:

            内联代码的优先级高于其他代码。要调用你的其他函数 func() 从 f1() 调用它。

            在你的函数中,添加一行,

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

            重写整个代码,

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

            【讨论】:

            • “内联代码的优先级高于其他代码”这是什么意思?
            猜你喜欢
            • 2016-09-27
            • 2021-12-29
            • 2023-01-29
            • 1970-01-01
            • 2014-10-15
            • 2016-11-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多