繁体   English   中英

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

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

我正在一个网站上,如果单击内部“ _blank”目标链接,它将尝试将JSON内容加载到DIV元素中。 如果JSON提取/加载失败,则链接应正常运行。

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;
    });
});

现在,单击a元素会导致JSON加载,但它也会立即将链接启动到“ _blank”标签中。

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

通过阻止默认设置并手动打开选项卡,如下所示:

$(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
    });
});

首先,在“ $(this).click”中,我不确定“ this”是什么,所以这就是我要做的方式。 而不是让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);
    });
});

在传递给click()的函数的末尾使用event.preventDefault() ,如果要在失败时转到该位置,则捕获URL并使用类似以下内容的方法手动更改位置

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

失败。

暂无
暂无

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

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