[英]Naming a function that loads on document ready
I have got a .js file that adds functionality to a menu when the page loads (when document is ready) ... the first three lines of the file are... 我有一个.js文件,可在页面加载时(当文档准备好时)为菜单添加功能...文件的前三行是...
( function( $ ) {
$( document ).ready(function () {
$('#cssmenul li.has-sub>a').on('click', function(){
After that there's loads more code that adds colours and other visual effects. 之后,将加载更多代码,以添加颜色和其他视觉效果。
At the moment the function doesn't have a name - it just runs. 目前,该函数还没有名称-只是运行。 However if I wanted to call the function from a button how do I name it?
但是,如果我想通过按钮调用该函数,该如何命名? If called the function activateMenu I would then have a button like this:
如果调用函数activateMenu,我将有一个像这样的按钮:
<input type="button" value="Activate" onclick="activateMenu();">
Thanks very much 非常感谢
If you want to reuse the code as activateMenu
, then you can group the contents of that code into its own function and reference it inside your .ready()
如果要将代码重用为
activateMenu
,则可以将该代码的内容分组到其自己的函数中,并在.ready()
引用它。
(function($){ $(document).ready(function(){ activateMenu(); }); })(jQuery); function activateMenu(){ console.log('test'); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="activateMenu()">Test Button</button>
create your function separately and the just pass the reference of it to the ready
event, like this, 分别创建函数,然后将其引用传递给
ready
事件,例如,
function doSomething(){ // do whatever you want to do console.log('doing something') } // then $( document ).ready(doSomething)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="doSomething()">click me</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.