开发者

Overriding default behaviour of anchor tags using jquery

开发者 https://www.devze.com 2023-02-15 05:29 出处:网络
I am trying to override the default behaviour of an anchor tag so i can load in a web page on my server into the exisiting div, rather than a new tab or window.

I am trying to override the default behaviour of an anchor tag so i can load in a web page on my server into the exisiting div, rather than a new tab or window.

so far i have:

myContainer.click(function(){                   
                    event.preventDefault();
                    $('a').click(function(){
                        var link = $(this).attr('href');
                        myContainer.load(link);
                    });
            });

In chrome i have to click the link twice before it does anything, in IE an FF it doesnt work at all and refreshes the page with the new link.

Any he开发者_JAVA技巧lp is much appreciated.


Shouldn't it be just:

 $('a').click(function(e) {
     e.preventDefault(); 
     myContainer.load(this.href);
 });

Your code assigns a click handler inside a click handler. So the first click will attach the click handler to the link, and the second click (on the link) will execute the new click handler.

It seems you only need one click handler. If the links are added dynamically, you can use .on() (the successor of .live and .delegate):

myContainer.on('click', 'a', function(e) {
     e.preventDefault(); 
     myContainer.load(this.href);
});

// or

$(document).on('click', 'a', function(e) {
     e.preventDefault(); 
     myContainer.load(this.href);
});


you forgot to pass in event:

myContainer.click(function(event){
event.preventDefault();
 $('a').click(function(){ var link = $(this).attr('href');
 myContainer.load(link);
 });
 });

try to rearrange them:

myContainer.ready(function(){
    $('a').click(function(event){
    event.preventDefault();
    var link = $(this).attr('href');
     myContainer.load(link);
     });
     });
0

精彩评论

暂无评论...
验证码 换一张
取 消