获取数据属性值...数据返回null

时间:2013-04-12 14:32:22

标签: jquery

我有以下标记:

<a href="#" class="Test" data-url="/api/users/unlock">Test</a>

以下JQuery:

$('a.Test').click(function (e) {
  alert(e.data); >> This returns null
  jQuery.support.cors = true;
  $.ajax({
    url: e.data('url'),
    type: 'GET',
    dataType: 'json',
    success: function (data) {
      alert(data)
    },
    error: function () {
      alert("Failure!");
    }
  });

});

基本上,我试图在Ajax中使用data-url的url。

这不起作用,当我尝试提醒(e.data)时,我得到空。

我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:4)

您需要使用data()函数,例如:

您需要$(this).data("url");

并且,要注意,$(this)将在$ .ajax调用中失去范围,因此请务必在其外部设置变量并使用它。即。

$('a.Test').click(function (e) {
  var url = $(this).data("url");
  jQuery.support.cors = true;
  $.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    success: function (data) {
      alert(data)
    },
    error: function () {
      alert("Failure!");
    }
  });