0

我需要更改锚中的href,然后在新窗口中打开链接,但是这段代码不起作用。有任何想法吗?显然ajax调用返回的url是正确的。

<a href="http://www.google.com" target="_blank">alink</a>
$(document).ready(function(){

    $('a').on('click', function(e){
         e.preventDefault(); 
         _this = $(this);
         $.ajax({ type:"GET", url:A_URL, dataType:"json",
               success: function(data){                                     
                        var u = data.results[0].trackViewUrl;
                        _this.attr('href', u);                              
                        window.open(u, '_blank');               
               }            
        })
    })

})
4

2 回答 2

3

如果您只想更改 url 并在新窗口中打开:

$(document).ready(function () {
    $('a').on('click', function (e) {
        $(this).attr("href", "new Url");
        $(this).attr("target", "_blank");
    })
})

但是如果你想通过 ajax 获取新的 url:

$(document).ready(function () {
    $('a').on('click', function (e) {
        var $this = $(this);
        $.ajax({
            url: 'GetUrl',
            async: false,
            success: function (url) {
                $this.attr("href", url);
                $this.attr("target", "_blank");
            },
            error: function () {
                e.preventDefault();
            }
        });
    })

})
于 2012-07-12T13:59:39.340 回答
0

试试这个

$('a').on('click', function(e){
     e.preventDefault(); 
     var me = $(this);

     $.get(
         A_URL,
         {},
         function(data) {
              var u = data.results[0].trackViewUrl;
              me.attr('href', u);                              
              window.open(u, '_blank');      
         },
         'JSON'

     );
})
于 2012-07-12T13:55:02.590 回答