如何确保始终禁用链接的默认操作? [英] How can I ensure that a link's default action is always disabled?

查看:87
本文介绍了如何确保始终禁用链接的默认操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开展一个项目,我正在使用大量的ajax调用来使网站交互更加优雅。我一直在使用的过程是获得脚本的链接,该脚本执行在链接标记中存储为href的相应操作。然后我使用jquery来定位该元素并禁用默认操作并执行ajax调用。

I'm working on a project where I'm using a lot of ajax calls to make the the site interaction more elegant. The process I have been using is to have the link to the script that executes the appropriate action stored as the href in a link tag. I then use jquery to target that element and disable the default action and execute the ajax call.

问题是有时 $(文件).ready()功能无法正常执行或在用户点击链接之前执行被延迟。这导致页面通过正常的浏览器加载打开。

The problem is that on occasion the $(document).ready() function doesn't properly execute or is delayed in executing before a user can click the links. This results in the page being opened via normal browser load.

我已经实现了代码,用于检测代码是通过ajax还是通过浏览器执行,所以所有这些都是加载空白页面。在某些情况下,我可以让它检测执行类型并以不同的方式响应,但在其他情况下,如果它不是由ajax执行则会导致问题。

I have implemented code that detects if the code is being executed via ajax or via the browser so all that happens is that a blank page is loaded. In some cases I can have it detect the execution type and respond differently but in other cases, if it's not executed by ajax then it causes problems.

有没有办法确保链接的默认操作始终被禁用,无论页面的加载进度如何,或者是否有比我正在采用的方法更好的方法?

Is there a way to ensure that the link's default action is disabled at all times regardless of the page's loading progress or is there a better approach than the one I'm taking?

推荐答案

您可以在全局范围内运行代码,只需将JS代码块放在DOM元素(链接)之后正在与...合作。这样您就不依赖于事件处理程序来触发。在结束< / body> 标记之前放置代码块是个好地方。

You can run the code in the global scope, just place the JS code block after the DOM elements (links) you are working with. This way you aren't relying on an event handler to fire. Placing the code block just before the closing </body> tag is good place.

    <a class="my-links" href="/path/to/server-side.***"></a>
    <script>
    function myFunc () {
        $.ajax({
            url     : $(this).attr('href'),//use the href attribute for the link clicked as the URL for the AJAX request
            type    : 'get',
            success : function (serverResponse) {
                alert('Success');
            },
            error   : function () {
                alert('Error');
            }
        });

        //in a jQuery event handler, returning false is the same as calling: event.preventDefault(); event.stopPropagation()
        return false;
    }
    $('.my-links').bind('click', myFunc);
    </script>

</body>

这篇关于如何确保始终禁用链接的默认操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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