I have a page which uses jQuery document.ready
, t开发者_如何学运维o populate the content of a div when a button is clicked.
The content inside the div also uses jquery to create some hover preview of an image (also inside this div). But I can not use document.ready
again. How should this be implemented?
You can use document.ready
as many times as you like. They're executed top-to-bottom.
Use callbacks or functions. Or both.
$(document).ready(function(){
$(element).click(function(){
alert('bla')
});
$(element).hover(function(){
call_alert('bla');
});
});
function call_alert(stringer) { alert(stringer) }
if you do the following, it is similar to document.ready
(function(){
//your code here
alert('this fired when the dom was ready');
})();
Really though the question isn't actually related to document.ready. That just makes it so the script isn't executed until everything in the dom is loaded into browser cache. Basically just create your function to bind the button click to then on its call back bind the hover function to the image. Otherwise look into the .live() function for the images.
$(document).ready(function() { })
Simply says execute the code within this anonymous function on the ready event of the document object, an event which fires when the dom is loaded.
Within that you can have as many functions assigned to as many events as you wish.
Javascript is parsed before the dom is loaded, and all the functions are bound to the events in the browser's memmory. So, what you are saying is bind all these functions to all these events but only after the dom is ready, which saves it looking for elements that haven't been parsed yet.
You can do it like this
$(document).ready(function() {
$("h1").click(function() {
alert("Someone clicked h1");
});
$("h2").hover(function() {
alert("someone is hovering our h2s"); //never do this as it will fire endless alerts and crash the browser.
})
})
Or like this:
function hover_func(el) {
alert("someone is hovering over"+el.tagName);
}
function hover_func(el) {
alert("someone clicked"+el.tagName);
}
$(document).ready(function() {
$("h1").click('click_func($(this))');
$("h2").hover('hover_func($(this))');
})
精彩评论