Preventing bubbling after loading?
I've a huge problem开发者_JS百科.
I'm having a div named "#box" that loads external content after clicking links in it:
$("#box a").click(
function(e)
{
e.preventDefault();
var hash = this.parentNode.hash;
$("#boxLoaded").load('boxFiles/'+ hash.substring(1) +'.html');
$("#box").fadeOut(100);
$("#boxLoaded").fadeIn(200);
});
Easy so far :)
When somebody clicks anywhere in "#boxLoaded" it disappears and loads box again, so it looks like in the beginning:
$("#boxLoaded").click(
function()
{
$("#boxLoaded").fadeOut(200);
$("#box").show();
});
The problem is I have a menu named "box-menu" in loaded files (inside of #boxLoaded) and when somebody clicks them - the code above is being executed (fading out #BoxLoaded and showing #Box).
I want to prevent it from happening, but:
$("#box-menu").click(
function(e)
{
e.preventDefault()
});
What to do? It works fine, when I'm not loading() these files...
You just need to switch to .live()
and stop the bubbling via event.stopPropagation()
here:
$("#box-menu").live("click", function(e) {
e.stopPropagation();
});
Alternatively, you can re-bind then loading, changing this:
$("#boxLoaded").load('boxFiles/'+ hash.substring(1) +'.html');
To this:
$("#boxLoaded").load('boxFiles/'+ hash.substring(1) +'.html', function() {
$("#box-menu").click(function(e) { e.stopPropagation(); });
});
By calling e.preventDefault()
you are only preventing the link from resuming its default event. After the link has been clicked on the containing div #boxLoaded
still has its onclick()
command. Instead of using e.preventDefault()
try return false
. I think that should do the same as preventDefault()
in this case and also abort the commands that follow.
-- I cant comment on peoples posts yet but in response to Nick, 'thats cool, didn't realise there was a e.stopPropagation()
function'
精彩评论