如何使用jquery从<a>标签获取完整的URL

Has*_*mud 1 php url jquery redirect undefined

我有通知div.当有人单击其中一个链接时,通知的数量将会更改,之后用户将被重定向到他单击的链接.这是里面的php脚本div.

<?php
 while($row = stmt->fetch(PDO::FETCH_OBJ))
 {
 echo "<p><a href='http://example.com/blog/index.php?t_id=".$t_id."&c_id=".$c_id."'>".$title."</a></p>";
 }
?>
Run Code Online (Sandbox Code Playgroud)

我在里面使用以下Jquery div:

<script>
 $('p').click(function(event){
 event.preventDefault();

 $.ajax({
 type: "POST",
 url: "http://www.example.com/change_notification.php"
 })
 .done(function( msg ) {

 $("#changed_notification_value").text( msg );
 var n_url = $('a', this).attr('href');
 window.location.href = n_url;

 });
});
</script>
Run Code Online (Sandbox Code Playgroud)

通知编号成功更改但在尝试重定向时,n_url显示的值未定义.

gpo*_*eur 7

我认为你在使用时有范围问题this.你可以做这样的事情来解决问题.n_url在发出ajax请求之前获取.

$('p').click(function (event) {
    event.preventDefault();
    var n_url = $('a', this).attr('href');

    $.ajax({
        type: "POST",
        url: "http://www.example.com/change_notification.php"
    }).done(function (msg) {

        $("#changed_notification_value").text(msg);
        window.location.href = n_url;
    });
});
Run Code Online (Sandbox Code Playgroud)