简体   繁体   中英

Disable href link with jQuery click event if valid JSON is found/ returned

I'm working on a site where if a internal "_blank" targeted link is clicked it attempts to load JSON content into a DIV element. If the JSON fetch/ load fails the link should work as per normal.

HTML:

<a href="/glossary/definition" target="_blank">Technical Term</a>

jQuery:

$(this).click(function () {
  var helperData = $.getJSON(jsonURL, function () {})
    .done(function (data) {
      $('#helper-text').html('<h1>' + data.Title + '</h1><hr/>' + data.Content);
      return false;
    })
    .fail(function () {
      console.log('JSON error: ' + jsonURL);
      return true;
    });
});

At the moment clicking the a element causes the JSON to load, but it also immediately launches the link into a "_blank" tab.

How do I have it wait to see if the JSON is fetched/ loaded before launching the link - and disable the link if the JSON is fetched/ loaded?

By preventing default and opening the tab manually like so:

$(this).click(function (e) {
  e.preventDefault(); // Halt the tab from opening
  var helperData = $.getJSON(jsonURL, function () {})
    .done(function (data) {
      $('#helper-text').html('<h1>' + data.Title + '</h1><hr/>' + data.Content);
    })
    .fail(function () {
      console.log('JSON error: ' + jsonURL);
      window.open(jsonURL, '_blank'); // Open the tab manually
    });
});

First the in the '$(this).click' I'm not sure what "this" is so here's the way I would do it. Rather than letting the click event happen get the url and if your ajax call fails then open a new window to the url.

$('a[target="_blank"]').click(function (e) {
  e.preventDefault();
  var url = $(this).attr("href");
  var helperData = $.getJSON(jsonURL, function () {})
    .done(function (data) {
      $('#helper-text').html('<h1>' + data.Title + '</h1><hr/>' + data.Content);
    })
    .fail(function () {
      console.log('JSON error: ' + jsonURL);
      window.open(url);
    });
});

Use event.preventDefault() at the end of the function passed to click(), and if you want to go the the location on failure then catch the url and change the location manually using something like

var $link = $(this).attr('href');
window.location = $link;

on failure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM