javascript - DOM find ID returns undefined -
i getting undefined error whenever click body elements. not sure where's issue..
$('body').on('click',function() { console.log($(this).attr('id')); })
in jquery event callbacks this
context equal object on assign event. $('body').on('click'
callback this
body
dom element, wherever user clicked.
if want top clicked element, need access event's target
property:
$('body').on('click', function(e) { console.log(e.target.id); // "" if no id presented });
check snippet out:
$('body').on('click', function(e) { $("#result").text(e.target.id === "" ? "no id" : e.target.id); });
div { display: inline-block; width: 50px; height: 50px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div style="background-color: red;" id="red"></div> <div style="background-color: green;" id="green"></div> <div style="background-color: blue;" id="blue"></div> <div style="background-color: black;" id="black"></div> <div style="background-color: yellow;"></div> <br/><span id="result"></span>
Comments
Post a Comment