简体   繁体   English

onclick函数需要执行一个简单的javascript函数

[英]onclick function need to execute a simple javascript function

I have a button where I am trying to add on click jquery as below 我有一个按钮,我尝试在其中添加点击jQuery,如下所示

<button onclick="myFunction()">YES</button>

And

$(document).ready(function() {
    function myFunction(){
        $('#mycheckboxdiv').toggle();
        $("div#headersteptwo").addClass("hidden");        
    }
})

However, on click I am getting Uncaught ReferenceError: myFunction is not defined 但是,单击时我会收到Uncaught ReferenceError:未定义myFunction

What am I doing wrong and how to fix this? 我在做什么错以及如何解决这个问题?

Updated with a sample jsfiddle 更新了一个示例jsfiddle

http://jsfiddle.net/3aC7W/1/ http://jsfiddle.net/3aC7W/1/

What am I doing wrong and how to fix this? 我在做什么错以及如何解决这个问题?

You are defining the function inside another function, ie the function is not defined in global scope and hence cannot be found by the inline event handler. 您正在另一个函数中定义函数,即该函数在全局范围内定义,因此内联事件处理程序无法找到该函数。

Just remove $(document).ready(function() { because you don't need it there: 只需删除$(document).ready(function() {因为您在那里不需要它:

function myFunction(){
    $('#mycheckboxdiv').toggle();
    $("div#headersteptwo").addClass("hidden");        
}

You only have to use $(document).ready(function() { ... }); 您只需要使用$(document).ready(function() { ... }); if you manipulate the DOM, and also only if you place the script before the elements in the HTML document. (如果您操作DOM,并且仅当您将脚本放在HTML文档中的元素之前)。


The better solution of course would be to bind the event handler with jQuery (and not use inline event handlers): 当然,更好的解决方案是将事件处理程序与jQuery绑定(而不使用内联事件处理程序):

$(document).ready(function() {
    $('button').on('click', function(){
        $('#mycheckboxdiv').toggle();
        $("div#headersteptwo").addClass("hidden");        
    });
});

You might have to add a class or ID to the button to make the selector more specific. 您可能必须在按钮上添加一个类或ID,以使选择器更加具体。 Have a look at the list of available selectors . 看一下可用选择器列表

change your code to this way to achieve click : 将您的代码更改为此方式以实现click:

<button id="myFunction">YES</button>

and

$(document).ready(function() {
    $('#myFunction').click(function(e){
        $('#mycheckboxdiv').toggle();
        $("div#headersteptwo").addClass("hidden");
    });
});

check it at: http://jsfiddle.net/aneesh_rr/XJ758/3/ 在以下位置检查它: http : //jsfiddle.net/aneesh_rr/XJ758/3/

change your code to this: 将您的代码更改为此:

$(document).ready(function() {
    window.myFunction = function(){  //you should make myFunction avaliable in global
        $('#mycheckboxdiv').toggle();
        $("div#headersteptwo").addClass("hidden");        
    }
})

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

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