简体   繁体   English

如果找到/返回有效的JSON,则禁用带有jQuery click事件的href链接

[英]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. 我正在一个网站上,如果单击内部“ _blank”目标链接,它将尝试将JSON内容加载到DIV元素中。 If the JSON fetch/ load fails the link should work as per normal. 如果JSON提取/加载失败,则链接应正常运行。

HTML: HTML:

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

jQuery: 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. 现在,单击a元素会导致JSON加载,但它也会立即将链接启动到“ _blank”标签中。

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? 我如何等待启动链接之前先查看是否已获取/加载JSON-如果已获取/加载JSON,则禁用该链接?

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. 首先,在“ $(this).click”中,我不确定“ this”是什么,所以这就是我要做的方式。 Rather than letting the click event happen get the url and if your ajax call fails then open a new window to the url. 而不是让click事件发生,而是获取URL,如果您的Ajax调用失败,则打开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 在传递给click()的函数的末尾使用event.preventDefault() ,如果要在失败时转到该位置,则捕获URL并使用类似以下内容的方法手动更改位置

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

on failure. 失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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