0

我是 Jquery 的新手并尝试发出 http 请求,这样我就不必离开当前页面,但是

var getURL = $("#callerId").attr("href"); 

似乎没有工作 console.log(getURL) 显示“未定义”

有源代码(到 callerId 的所有内容都应该是正确的)

    <script type = "text/javascript">

$(document).ready(function() {
    $('ul.hrefURL a').click(function(dontRedirect) {
        dontRedirect.preventDefault(); 
        var callerId = event.target.id;
        var getURL = $("#callerId").attr("href");
        $.ajax({
            type : "GET",
            url: getURL,
            success: function(response){
                alert($('#response'));  
            }
        });

    });
});

</script>


<a href="javascript:document.location = TTS1" id = "1T">
4

2 回答 2

2

你需要使用

var getURL = $(this).attr("href");

代替

var getURL = $("#callerId").attr("href");

在第一种情况下$(this),指向您刚刚单击的锚点的 jquery 对象,在第二种情况下 - 它指向您的示例甚至未涵盖的某些元素

现场示例:http: //jsfiddle.net/zerkms/YJRLR/

于 2012-05-09T21:03:45.253 回答
1

我认为您打算这样做:

<script type = "text/javascript">

$(document).ready(function() {
    $('ul.hrefURL a').click(function(e) {
        e.preventDefault(); 
        var getURL = this.href;
        $.ajax({
            type : "GET",
            url: getURL,
            success: function(response){
                alert($('#response'));  
            }
        });

    });
});

</script>

关于您以前的代码需要了解的事项:

  1. this将自动设置为导致事件的对象,因此您不必获取target.id.
  2. You can get the value of href with this.href. There is no need to use jQuery for that.
  3. If you wanted to make the value of this into a jQuery object, you would do it with $(this) or with $(e.target.id). You use strings with jQuery when it's a CSS selector. You use variable values directly when you already have the object reference.
于 2012-05-09T21:05:32.053 回答