[英]anchor tag data not accessible when clicking on glyphicons inside the anchor tag
How do I get the data when there is only a glyphicon in the anchor tag? 当锚标签中只有一个glyphicon时,如何获取数据? Below is a demonstration of the problem... 以下是问题的演示...
http://jsfiddle.net/sua0yp4y/2/ http://jsfiddle.net/sua0yp4y/2/
HTML: HTML:
<h1 id="output1">OUTPUT1</h1>
<h1 id="output2">OUTPUT2</h1>
<a class="withIcon" href="#" data-taskid="1123" data-userid="5813"><span class="glyphicon glyphicon-time"></span></a>
<h1 id="output3">OUTPUT3</h1>
<h1 id="output4">OUTPUT4</h1>
<a class="withoutIcon" href="#" data-taskid="1123" data-userid="5813">without icon</a>
JS: JS:
$('body').on('click','a.withIcon',function(e){
e.preventDefault();
$("h1#output1").text($(e.target).data('userid'));
$("h1#output2").text($(e.target).data('taskid'));
});
$('body').on('click','a.withoutIcon',function(e){
e.preventDefault();
$("h1#output3").text($(e.target).data('userid'));
$("h1#output4").text($(e.target).data('taskid'));
});
Add the closest('a') to find the closest anchor tag and get the data values: 添加最接近的('a')以找到最接近的锚标记并获取数据值:
$("h1#output1").text($(e.target).closest('a').data('userid'));
$("h1#output2").text($(e.target).closest('a').data('taskid'));
http://jsfiddle.net/sua0yp4y/3/ http://jsfiddle.net/sua0yp4y/3/
Use this
instead of e.target
to referece the element you clicked on. 使用this
而不是e.target
引用您单击的元素。
Updated Fiddle - http://jsfiddle.net/sua0yp4y/5/ 更新的小提琴-http: //jsfiddle.net/sua0yp4y/5/
$('body').on('click','a.withIcon',function(e){
e.preventDefault();
$("h1#output1").text($(this).data('userid'));
$("h1#output2").text($(this).data('taskid'));
});
$('body').on('click','a.withoutIcon',function(e){
e.preventDefault();
$("h1#output3").text($(this).data('userid'));
$("h1#output4").text($(this).data('taskid'));
});
将$(e.target)替换为$(this),即可解决问题。
demo http://jsfiddle.net/sua0yp4y/8/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.