如何使用 jQuery 单击事件基于 JSON 查询异步更改 href 值

发布于 2024-08-08 20:31:05 字数 1277 浏览 4 评论 0原文

我正在使用 bit.ly 网址缩短服务 来缩短发送到“在 Twitter 上分享”功能的某些网址。我想仅在用户实际按下共享按钮时加载 bit.ly url(由于 bit.ly 的最多 5 个并行请求限制)。 Bit.ly 的 REST API 返回带有缩短网址的 JSON 回调,这使得整个场景异步。

我已尝试以下方法来停止单击事件,并等待 JSON 调用返回值,然后再启动单击。

我在 jQuery(document).ready() 中有以下简化代码:

更新的代码(过于简化)!

jQuery("#idofaelement").click(function(event) {
    event.preventDefault(); //stop the click action
    var link = jQuery(this);
    bitlyJSON(function(shortUrl) {
        link.attr("href", function() {
          //process shortUrl
          //return finalized url;                   
        }).unbind().click();
    });
});

以及以下代码来处理位缩短(效果很好):

function bitlyJSON(func) {
//
// build apiUrl here
//
jQuery.getJSON(apiUrl, function(data) {
    jQuery.each(data, function(i, entry) {
        if (i == "errorCode") {
            if (entry != "0") {
                func(longUrl);}
        } else if (i == "results") {
            func(entry[longUrl].shortUrl);}
    });
});  
} (jQuery)

href 的值发生了变化,但最终的 .click() 事件永远不会被触发。在为 href 定义静态值时,这可以正常工作,但在使用异步 JSON 方法时则不行。

I'm using the bit.ly url shortening service to shorten certain url's being sent to a "share on twitter" function. I'd like to load the bit.ly url only when a user actually presses the share button (due to bit.ly's max 5 parallel reqs limitation). Bit.ly's REST API returns a JSON callback with the shortened url, which makes the whole scenario async.

I've tried the following to stop the click event, and wait for the JSON call to return a value before launching the click.

I have the following simplified code in jQuery(document).ready():

Updated code (oversimplified)!

jQuery("#idofaelement").click(function(event) {
    event.preventDefault(); //stop the click action
    var link = jQuery(this);
    bitlyJSON(function(shortUrl) {
        link.attr("href", function() {
          //process shortUrl
          //return finalized url;                   
        }).unbind().click();
    });
});

And the following code to handle the bitly shortening (works just fine):

function bitlyJSON(func) {
//
// build apiUrl here
//
jQuery.getJSON(apiUrl, function(data) {
    jQuery.each(data, function(i, entry) {
        if (i == "errorCode") {
            if (entry != "0") {
                func(longUrl);}
        } else if (i == "results") {
            func(entry[longUrl].shortUrl);}
    });
});  
} (jQuery)

The href gets its value changed, but the final .click() event never gets fired. This works fine when defining a static value for the href, but not when using the async JSON method.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

海之角 2024-08-15 20:31:05

正如您自己概述的那样:

event.preventDefault(); //stop the click action

这意味着,浏览器不会转到该 URL,如果您希望实际转到长 URL 位置,只需执行以下操作:

document.location.href = longurl;

As you outlined yourself:

event.preventDefault(); //stop the click action

That means, BROWSER IS NOT GOING TO THAT URL, if you wish to actually go forward to the long-url location, simply do something like:

document.location.href = longurl;
能否归途做我良人 2024-08-15 20:31:05

iirc,jquery 不会触发 A 元素上的“点击”。我会在回调中尝试旧的好的“location.href=whatever”。

 bitlyJSON(function(shortUrl) {
      link.attr("href", function() {
      //process shortUrl
      //return finalized url;                   
    });
    location.href = link.attr("href");
});

iirc, jquery doesn't trigger "click" on A elements. I'd try old good "location.href=whatever" in the callback.

 bitlyJSON(function(shortUrl) {
      link.attr("href", function() {
      //process shortUrl
      //return finalized url;                   
    });
    location.href = link.attr("href");
});
苯莒 2024-08-15 20:31:05

我认为您真正想要的是从点击事件中返回 false; ,以防止实际跟随 href,对吗?

喜欢:

jQuery("#idofaelement").click(function(event) {
    //event.preventDefault(); //stop the click action
    var link = jQuery(this);
    bitlyJSON(function(shortUrl) {
        link.attr("href", function() {
        //process shortUrl
        //return finalized url;                   
        }).unbind().click();
    });
    return false;
});

I think what you actually want is to return false; from the click event, to prevent the actual following of the href, right?

Like:

jQuery("#idofaelement").click(function(event) {
    //event.preventDefault(); //stop the click action
    var link = jQuery(this);
    bitlyJSON(function(shortUrl) {
        link.attr("href", function() {
        //process shortUrl
        //return finalized url;                   
        }).unbind().click();
    });
    return false;
});
つ可否回来 2024-08-15 20:31:05

@Tzury Bar Yochay 建议我使用 location.href 更新网址,为我指明了正确的方向。 @Victor 也帮助了他的回答。

我把答案结合起来有点工作,但对 Firefox 的历史有疑问。似乎更新 window.location 确实重定向了用户,但也删除了“历史记录中的源页面”。这在 chrome、safari、ie8、ie8 兼容性或 ie7 中不会发生。

基于对另一个问题的回答我能够创建一个解决方法,给出以下工作代码+进行一些更改:

jQuery("#idofaelement").one("click", function(event) {
    bitlyJSON(function(shortUrl) {
        jQuery("#idofaelement").attr("href", function() {
            //process shortUrl
            //return finalized url;                   
        });
        setTimeout(function() {
            window.location = jQuery("#idofaelement").attr("href");
        }, 0);
    });
    return false;
});

感谢所有帮助!

@Tzury Bar Yochay pointed me in the right direction by suggesting I use location.href to update the url. Also @Victor helped with his answer.

I got things kinda working combining the answers, but had issues with the history in firefox. Seems that updating window.location indeed redirected the user, but also removed the "source page" from the history. This did not happen in chrome, safari, ie8, ie8-compatibility or ie7.

Based on this response to another question I was able to create a workaround giving the following working code + made a few changes:

jQuery("#idofaelement").one("click", function(event) {
    bitlyJSON(function(shortUrl) {
        jQuery("#idofaelement").attr("href", function() {
            //process shortUrl
            //return finalized url;                   
        });
        setTimeout(function() {
            window.location = jQuery("#idofaelement").attr("href");
        }, 0);
    });
    return false;
});

Thanks for all the help!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文