请问是否有一种方法可以将jquery与链接连接起来,当用户单击链接或切换到链接并按下Enter时运行函数。
我想在页面更改之前拦截链接的激活并执行操作,但无论哪种情况都要这样做。
无论哪种情况,'click'事件都会触发,这将得到你想要的结果:
$('a').click(function(){
alert('perform action here');
});
其实很简单... 在一个元素上按下回车键时,它在浏览器中的行为就像是点击。不需要做任何特殊处理。
$('a.links_to_bind').bind('click', function() {
/* do your stuff... */
return false;
});
编辑:
如果您希望在完成操作后页面发生变化,您可能需要添加一个条件语句到return false
。例如:
if(everythings_good) {
return true;
} else {
return false;
}
$('a').keydown(function() {
return false; // Prevent default action
});
$('a').keyup(function(event){
if(event.keyCode == '13'){
$(this).find('button.mychoice').click();
}
});
// This does the trick for both IE and FF.
this.href;
或者在某些浏览器中,this.getAttribute('href');
对于那部分来说,不需要使用jQuery(或者不应该使用)。 - David Thomas