JQuery: exchange function between page code and document.ready code

I have good dialogs defined as such in jQuery:

<script type="text/javascript"> $(document).ready(function() { $( "#someDialog" ).dialog({ autoOpen: false, model: true, buttons: { "Do Something": function() { var cleanInput = sanitizeInput(input); // Do something with the clean input }, Cancel: function() { $( this ).dialog( "close" ); } }, close: function() { } }); function sanitizeInput(input) { // Some magic here return input; } }); </script> 

Somewhere on a non-dialog page, I have an element that calls a function with a parameter:

 <a href="#" onclick="doSomething('wendy');">Wendy stats</a> 

And the related JavaScript:

 <script type="text/javascript"> function doSomething(input) { var cleanInput = sanitizeInput(input); // Some code here } </script> 

I would like to reuse the sanitizeInput () function for this function. However, outside the scope of the document.ready function, the dialog does not work. Enabling the doSomething () function inside the document.ready function also violates it. So where can I put the sanitizeInput () function so that both can use it?

Thanks.

+4
source share
2 answers

You just need to move the function outside of the ready() callback.

 $(document).ready(function() { $( "#someDialog" ).dialog({ autoOpen: false, model: true, buttons: { "Do Something": function() { var cleanInput = sanitizeInput(input); // Do something with the clean input }, Cancel: function() { $( this ).dialog( "close" ); } }, close: function() { } }); }); /*** Make it global ***/ function sanitizeInput(input) { // Some magic here return input; } 

sanitizeInput() is now globally accessible, not limited to the scope of the ready() callback variables.

+3
source

In addition, I would suggest some small changes.

First of all, I would replace this:

 <a href="#" onclick="doSomething('wendy');">Wendy stats</a> 

with:

 <a href="#" data-name="wendy or server var">Wendy stats</a> 

and then add this to the end of the $(document).ready block:

 $("a[data-name]").click(function (e) { e.preventDefault(); doSomething($(this).data("name")); }); 
+2
source

Source: https://habr.com/ru/post/1391122/


All Articles