0

我有一个 html 元素,想在 OnClick 事件中读取数据属性

<a id="downloadFile" class="btn btn-success" href="javascript:;" data="MyData">Download file</a>

如果我使用下面的代码,请参考 href 属性而不是 A 元素。如何引用A元素并读取数据值?

 $('#downloadFile').click(function() {            
  alert(this.attr('data')); //I get error that 'href' do not has 'data' attribute, this code refers to href attribute and not to A element
});
4

4 回答 4

4

在事件处理程序的上下文中,this指的是 DOM 元素,而不是 jQuery 对象。用于$(this)获取一个 jQuery 对象,以便您可以使用该attr函数:

$('#downloadFile').click(function() {            
  alert($(this).attr('data'));
});

另一种选择是使用this.getAttribute("data").

演示

于 2012-10-22T15:01:40.957 回答
1

您可以拥有自定义数据属性并将其与-

现场演示

<a id="downloadFile" class="btn btn-success" href="javascript:;" data-yourhref="MyData">Download file</a>   

     $('#downloadFile').click(function() {            
        alert($(this).data('yourhref')); //Get error that href do not has data atribute, this refered to href atribute and not to A element
    });​
于 2012-10-22T15:01:14.627 回答
0

Only change THIS for the propper selector for Jquery

$('#downloadFile').click(function() {            
          alert($('#downloadFile').attr('data')); //Get error that href do not has data atribute, this refered to href atribute and not to A element
        });
于 2012-10-22T15:05:24.837 回答
0

您指的是使用 this 但使用 jquery 语法的 js 对象。

尝试:

$(this).attr('href')
于 2012-10-22T15:04:28.900 回答