【问题标题】:call function on button click does not work单击按钮时调用功能不起作用
【发布时间】:2017-01-13 11:43:00
【问题描述】:

我想在按钮点击事件上调用一个函数。该函数在另一个 js 文件中定义,我的function.php 文件中有enqueue 该文件。我可以看到文件已从enqueue 加载。但我得到了错误

errorReferenceError: myFunction 未定义

当我点击那个按钮时。我想在该按钮单击时显示下拉菜单

<button onclick="jQuery(document).ready(function($) {myFunction();});" class="dropbtn"><i class="fa fa-bars fa-lg" aria-hidden="true"></i></button>

custom.js

(function( $ ) {

    function myFunction() {

        document.getElementById( 'myDropdown' ).classList.toggle( 'show' );

    }

    window.onclick = function( event ) { 

        if ( !event.target.matches( '.dropbtn' ) ) {

        var dropdowns = document.getElementsByClassName( 'dropdown-content' );
        var i;

            for ( i = 0; i < dropdowns.length; i++ ) {

                var openDropdown = dropdowns[i];

                if ( openDropdown.classList.contains( 'show' ) ) {

                    openDropdown.classList.remove( 'show' );

                } 

            } 

        }

    }

})( jQuery );

【问题讨论】:

  • 只需将myFunction 从外部写入$(function() {})。你的锚属性应该是onclick=return myFunction();

标签: javascript php wordpress


【解决方案1】:

问题在于函数的范围,更详细的解释请参考this link。要解决它,请尝试在 js 文件本身中调用该函数。例如:

$(document).ready(function(){
    function myFunction(){
    ...
    }

    $(".dropbtn").click(myFunction());
});

【讨论】:

  • 显示相同的问题
  • 你确定你把函数和调用都放在同一个 jQuery 函数中吗?
  • 尝试参考stackoverflow.com/questions/5067887/…和其他类似问题。它很容易解决,但您只需要知道关键。
【解决方案2】:

应该有效

$(document).ready(function(){
    function myFunction(){
        alert ('Say something!');
    }

    $(".dropbtn").click(function(){
        myFunction();
    });
});

【讨论】:

    【解决方案3】:

    我注意到您不需要在按钮的onclick 属性中使用ready 函数,因此这就足够了:

    <button onclick="myFunction();" class="dropbtn">
      <i class="fa fa-bars fa-lg" aria-hidden="true"></i>
    </button>
    

    但是,您可以从按钮中删除 onclick 属性而不是这样做(出于代码可维护性和安全原因,避免内联脚本是一种很好的做法)并尝试 Manikiran 建议您的解决方案,但有一点不同, 你定义了myFunction不要执行它在custom.js:

    jQuery(function(){
      function myFunction(){
        jQuery( '#myDropdown' ).toggle( 'show' ); //this is the jQuery way
      }
    
      // remaining code of your custom.js
    
      jQuery(".dropbtn").click(myFunction); // binds the click event to
                                            // all the buttons with the dropbtn class
    });
    

    我注意到您在某些部分没有使用$,您可以将它们全部替换为jQuery 关键字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多