jQuery HTML 锚标记渐进增强
我编写了 jQuery,它应该找到特定的 标签并更改其行为。在 jQuery 加载之前,
标记具有指向另一个页面的 href 属性。我正在使用 jQuery 来更改
标记的行为,这样它就不会指示浏览器加载其他页面,而是在单击时运行 javascript,在
中动态加载内容
位于鼠标指针的位置。
因此,例如,我有以下内容: <代码>
<a class="funk" href="http://example.com/page2.html">Link</a>
<div class="hidden bubble">Load this instead.</div>
The jQuery I have running does the following: $(document).ready(function(){
$('.bubble').hide()
$('.bubble').removeClass('hidden');
$('.funk').attr('href', '#');
$('.funk').click(function(e){
$('.bubble').show();
})
})
我遇到的问题是:每当用户单击链接时,浏览器都会对 href="#"
属性进行操作,并将浏览器滚动到页面顶部。使我的网站最“正确”的方法是什么,以便浏览器根本不滚动,而只是执行我为单击事件编写的 jQuery 代码?
I have jQuery that I have written that is supposed to find a particular <a>
tag and change its behavior. Before jQuery loads, the <a>
tag has an href attribute that points to another page. I am using jQuery to change the behavior of the <a>
tag so that rather than directing the browser to load that other page, it instead runs javascript when clicked that loads content dynamically in a <div>
that is positioned at the location of the mouse pointer.
So, for example, I have the following:
<a class="funk" href="http://example.com/page2.html">Link</a> <div class="hidden bubble">Load this instead.</div>
The jQuery I have running does the following:
$(document).ready(function(){ $('.bubble').hide() $('.bubble').removeClass('hidden'); $('.funk').attr('href', '#');$('.funk').click(function(e){ $('.bubble').show(); })
})
The problem I have is: Whenever the user clicks the link, the browser acts on the
href="#"
attribute and brings scrolls the browser to the top of the page. What is the most "correct" way to make my site so that the browser does not scroll at all, but instead merely executes the jQuery code that I have written for the click event?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让“click”函数返回
false
。这会取消该事件,并且浏览器不会点击该链接。在这种情况下,您甚至可以让href
属性保持其原始值。为了保存,您可以显式取消该事件:
Let the 'click' function return
false
. That cancels the event, and the browser doesn't follow the link. In this case, you can even let thehref
attribute at its original value.To be on the save side, you can explicitly cancel the event:
将其添加到您的点击函数中:
这将执行方法名称所暗示的操作。
Add this to your click function:
This will do what is implied by the method names.
在点击处理程序中调用
e.preventDefault()
。http://api.jquery.com/event.preventDefault/
Call
e.preventDefault()
in the click handler.http://api.jquery.com/event.preventDefault/