JS和JQuery:只有在更改后才能获取新的href

时间:2012-07-20 05:08:22

标签: javascript button onclick

我有以下锚点

<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”实现这个想法,我当前的方式可能不正确。

3 个答案:

答案 0 :(得分:0)

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

您需要找到要执行此操作的元素。它既可以通过设置id然后使用document.getElementById()来完成,也可以使用Jquery选择器更容易地完成,甚至可以使用.click()来调用它。

答案 1 :(得分:0)

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

但是没有建议这个流程,我会在页面加载时更新这些hrefs,或者将默认URL设置到我的服务器页面,然后重定向到正确的日志文件

答案 2 :(得分:0)

你想要这样的东西

$(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类似的操作。您可以考虑,首先获取一个资源,该资源将预先告诉您正确的链接是什么。