简体   繁体   中英

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? Below is a demonstration of the problem...

http://jsfiddle.net/sua0yp4y/2/

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:

$('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:

$("h1#output1").text($(e.target).closest('a').data('userid'));
    $("h1#output2").text($(e.target).closest('a').data('taskid'));

http://jsfiddle.net/sua0yp4y/3/

The user clicks over the image you can change the event:

$('body').on('click','.glyphicon',function(e){
    e.preventDefault();
    $("h1#output1").text($(e.target).parent().data('userid'));
    $("h1#output2").text($(e.target).parent().data('taskid'));
});

fiddle

Use this instead of e.target to referece the element you clicked on.

Updated Fiddle - 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM