防止在.html和.append上跳转页面? [英] prevent page jump on .html and .append?

查看:65
本文介绍了防止在.html和.append上跳转页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用jquery .html或.append在DOM中添加元素时,页面会跳转到该位置.

when i use jquery .html or .append to add elements in the DOM the page jumps to that location.

我如何使其不跳跃,导致我希望我的用户能够单击将线程保存到收藏夹",而不会跳转至我保存的线程",则用户必须在列表中向下导航再次线程.

how can i make it not jumping, cause i want my users to be able to click on "save thread to favourites" and it wont jump to "my saved threads" cause then the user has to navigate down in the list with threads again.

我已经用过:

 // save thread
    $("a.save_thread").live("click", function(event) {
        event.preventDefault();
        $.post('controllers/ajaxcalls/threads.php', {method: 'save_thread', thread_id: event.target.id}, function(data) {
        }, 'json');
        return false;
    });

但是返回false并没有做任何事情.实际上,尽管它不使用append()或html(),但仍跳至页面开始位置.

but the return false didnt do anything. and actually, although it doesnt use append() or html() it still jumps to page start.

推荐答案

return falsepreventDefault是阻止链接被遵循的正确方法.检查您的JavaScript错误控制台.如果处理程序函数中存在异常,则不会返回false,而是会遵循该链接.

return false or preventDefault is the right thing to do to stop the link being followed. Check your JavaScript error console. If there is an exception in the handler function, it won't get to returning false and the link will get followed.

但是,您应该考虑将链接更改为<button>.您在这里拥有的不是链接,也不是到任何地方的连接;这是一个动作.按钮是一种更好的建模方式,因为它没有跟随链接的行为,也没有让用户单击鼠标中键以在新选项卡中打开链接目标或右键单击添加的行为.到书签(依此类推).因此,您不必担心阻止默认操作来停止页面移动.

However, you should consider changing your link to a <button>. What you have here is not a link, not a connection to any place in particular; it is an action. A button is a much better way of modelling that, because it doesn't have the behaviours of following a link, or allowing the user to middle-click to open the target of the link in a new tab, or right-click-add-to-bookmarks (and so on). As a consequence, you don't have to worry about preventing the default action to stop the page moving.

如果您不希望它看起来像3D按钮,则可以始终使用CSS重新设置其样式,例如. border: none; background: white; color: blue; text-decoration: underline;.尽管您无法完全在IE中重新设置其样式,但会错误地添加一些额外的填充,但这通常没关系.

If you don't want it to look like a 3D button you can always use CSS to restyle it, eg. border: none; background: white; color: blue; text-decoration: underline;. Whilst you can't totally restyle it in IE which erroneously adds a little extra padding, that typically doesn't matter.

这篇关于防止在.html和.append上跳转页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆