javascript 使用 jquery 覆盖锚标记的默认行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5207531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:22:18  来源:igfitidea点击:

Overriding default behaviour of anchor tags using jquery

javascriptjqueryanchor

提问by Julio

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.

我试图覆盖锚标记的默认行为,以便我可以将服务器上的网页加载到现有的 div,而不是新的选项卡或窗口。

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.

在 chrome 中,我必须在执行任何操作之前单击该链接两次,在 IE 和 FF 中它根本不起作用并使用新链接刷新页面。

Any help is much appreciated.

任何帮助深表感谢。

回答by Felix Kling

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 firstclick will attach the click handler to the link, and the secondclick (on the link) will execute the new click handler.

您的代码在单击处理程序中分配了一个单击处理程序。所以第一次点击会将点击处理程序附加到链接,第二次点击(在链接上)将执行新的点击处理程序。

It seems you only need oneclick handler. If the links are added dynamically, you can use .on()(the successor of .liveand .delegate):

看来您只需要键单击处理程序。如果链接动态添加,你可以使用.on()(的继任者.live.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);
});

回答by DrStrangeLove

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);
     });
     });