开发者

jquery - Block specific links before a page fully loads and binds click events

I have a modal dialog plugin written in jquery, that binds to the click event of all of the <a> elements with a specific class.

The modal dialog 'fetches' a page via AJAX, which is declared under the 'href' parameter of the <a> element.

Everything works fine, but - when a user clicks the <a> link before the page was fully loaded and ready (before the click event is binded to the element) - the browser navigates to the page declared in the 'href' parameter.

Any ideas of how to prevent this behavior? An ideal situation would be to ignore clicks on these elements before the page开发者_C百科 has fully loaded. Client-side performance is crucial.


If you need to avoid inline scripting, then you could utilise jQuery's live() method to bind an event handler for elements that have not yet been added to the DOM:

1) Be sure to include jQuery in the <head> and not the <body>, since we need to initiate the following code before any elements in the body are created.

2) Include the following, also in the <head> (e.g. as an external js file):

$("a").live("click", function(){// Use a more specific selector than "a" if poss.
  getAjax( // This is your Ajax function. Adapt as required.
      $(this).attr('href') // Pass in the <a>'s href attribute.
  );
  return false; // Cancel the default click handler, to prevent page redirect.
});


Typically you'll avoid directly coding any href into the tag. Instead set href="javascript:void(0)" and handle the submission with jQuery.

Do something like this:

<a onclick="SomeJQueryCall()" href="javascript:void(0)">Click Me!</a>

And here's the jQuery script:

function SomeJQueryCall() {
    //ask the web server for some AJAX xml
    $.get(SomeUrl, null, SomeCallBackFunction(), "xml");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜