Where to put my $(document).ready(function(){ When I have methods in a .js
I created a somefile.js where somefile.js contains some jQuery method. So for instance it conta开发者_JAVA百科ins this function:
function showWindow(divID)
{
var dialogDiv = $(divID);
dialogDiv.dialog
(
{
bgiframe: true,
modal: true,
autoOpen: false,
show: 'blind'
}
)
dialogDiv.dialog("open");
}
So in my .aspx page (or whatever, it could be an .html), I have a button:
<input type="button" onclick="showPopUp('testDiv')" value="Click Me!" />
My question is, we're going to use showPopUp all over in our app. If it's called from an onClick event, then where do I put my $(document).ready(function() since this code is not in the page, but in a .js file?
You can put it in the Javascript file if you want. If you're attaching listeners with the onclick attribute like that, you don't actually need to use $(document).ready().
However, it's generally considered better form to not use the onclick attribute, and attach the listener in Javascript, like so:
<input type = "button" class = "showPopup" id = "testDiv" value = "Click Me!" />
$(document).ready(function(){
$("input.showPopup").click(function(){
showWindow($(this).id);
}
function showWindow(id){...}
}
You can put that javascript in the head of the document like ~ricebowl said.
Put the $(document).ready(...);
in the head
of the (x)html page (or, indeed, .php, .aspx, etc) as normal, just so long as you make sure that it comes after the linked script
file (to load your somefile.js) and, of course, the link to your jQuery:
<head>
...
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="somefile.js"></script>
<script>
$(document).ready(
function() {
$('input[type=button]').click().showPopUp('testDiv');
}
)
</script>
</head>
Edited to note that I feel that I'm missing something obvious in your question. Please comment if I'm being completely obvious and missing your point...
The "right" technical answer will vary by framework (PHP, ASP.NET, etc.) If you want to use this function throughout your application, you can use a script tag:
<script type="javascript" src="somefile.js" />
That tag can be included in a "page header include", implemented in whatever way is best. For example, in ASP.NET I'd include that tag in the Master page.
You got to do this: Split the function into two:
MakeDialog(divID) //this way you prepare the div to be a dialog and ShowDialog(divID) //this is where you show the dialog
//document load
$(document).ready(function(){
MakeDialog(divId);//prepa
});
function makeDialog(divID)
{
var dialogDiv = $(divID);
dialogDiv.dialog
(
{
bgiframe: true,
modal: true,
autoOpen: false,
show: 'blind'
}
)
}
function showWindow(divId)
{
dialogDiv.dialog("open");
}
HTH
精彩评论