【问题标题】:JS and JQuery: Get the new href only after changing itJS 和 JQuery:仅在更改后获取新的 href
【发布时间】:2012-07-19 08:50:45
【问题描述】:

我有一个如下锚点

<a onclick="return getFile('/log/sample.log');" href="/log/sample.log" target="_blank"> sample.log </a>

因为在我的服务器上,href中的日志目录可能不正确。所以“getFile”函数会在询问服务器后将href更改为正确的。

由于链接不正确,第一次点击总是失败,然后在getFile中的AJAX过程完成并给出正确的href后,以后的点击就可以了。

问题是我如何强制让 html 在第一次点击时一直等待,直到 href 更改,然后在服务器上进行查询。

提前致谢。

我想我目前的方式可能不是正确的方向,使用“onclick”来实现这个想法。

【问题讨论】:

  • 在标签内使用 href="javascript:void(0)" 然后当点击标签时,它会调用 ajax 并在那里你会得到正确的路径。最后你可以设置 window.open = "your_file_absolute_path ";

标签: javascript button onclick


【解决方案1】:

你想要这样的东西

$(function() {

//assume you tagged all anchors you want to do this for with class=adjustlink
$('a.adjustlink').click(function(e) {
  var thisAnchor = $(this); //save reference for later use

  //this will either be true (see below) or undefined (falsy)
  if(thisAnchor.data('myapp.linkHasBeenTested')) {
    return;  //continue on
  } 

   // Stop the link from being navigated (the default for this event)
   e.preventDefault();

  //I'm assuming this is fetched as text but could just as well be JSON or anything else
  $.get('/LinkAdjustment/', thisAnchor.attr('href')).done(function(result) {
    thisAnchor.attr('href', result); //set the href
    thisAnchor.data('myapp.linkHasBeenTested', true);
    thisAnchor.trigger('click');
  });
});

});

作为一个有趣的旁注。您可能正在尝试执行类似于 REST is intended to be done 的方式。您可能会考虑,首先获取一个资源,该资源会预先告诉您正确的链接是什么。

【讨论】:

  • 整个想法太棒了。只有一个问题是关于“trigger('click')”的。它没有用。我试过“window.open”,也没有任何动作。
  • @Yang - 我能想到的唯一原因是如果你的弹出窗口阻止程序阻止了它(所有现代浏览器都内置了)。检查浏览器的显示区域。这是这个想法的一个工作示例:jsfiddle.net/gMN5X/1
  • 你是对的。 “window.open”现在正在工作,而不是“触发器”。对我来说,这就足够了。我仍然想知道为什么“触发器”仍然不起作用。我会检查更多。谢谢
  • @Yang - 我很确定这是因为弹出窗口阻止程序。上面使用“触发器”的示例对我来说非常有用。我对弹出窗口阻止程序如何工作的理解是,如果在用户交互和打开窗口之间经过了太多时间,他们会阻止它。可悲的是,除了对弹出窗口拦截器规则做出例外处理之外,别无他法。
【解决方案2】:

如果你想坚持这个流程,让你的 ajax 调用同步,它会强制等待。

但不建议使用此流程,我宁愿在页面加载时更新这些 href,或者将默认 url 设置为我的服务器页面,然后重定向到正确的日志文件

【讨论】:

    【解决方案3】:

    我建议最初将 href 设置为 #。在您的 getFile 中,将 href 设置为正确的值,然后以编程方式单击 ajax 成功时的“a”

    您需要找到执行此操作的元素。它可以通过设置一个 id 然后使用 document.getElementById() 来完成,或者使用 Jquery 选择器更容易做到这一点,它甚至有一个 .click() 你可以在之后调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      相关资源
      最近更新 更多