javascript - Unable to get the event target property of a named function -
in fiddle linked below there's example code need troubleshoot. i've simplified bit original code (didn't write) demo purposes in fiddle.
$(document).ready(function(){ $("ul").children().each(function(i){ $(this).click(function(){ var indexitem = i; if(indexitem == 0){ displayid(); } if(indexitem == 1){ displaynode(); } if(indexitem == 2){ displaynodevalue(); } }); }); }) function displayid(event){ // below returns undefined not want // var $listid = jquery(this).attr("id"); var $listid = event.target.id; alert($listid); } function displaynode(event){ var listnodename = event.target.nodename; alert(listnodename); } function displaynodevalue(event){ var listvalue = event.target.nodevalue; alert(listvalue); }
how event.target properties these items? console displays:
uncaught typeerror: cannot read property 'target' of undefined
i've googled various possible solutions below. i'm not finding answer.
how pass event object named function
getting id of element fired event
https://api.jquery.com/event.target/
if i've missed answer in threads, please let me know. seems question should answered somewhere, i'm having trouble locating it. if not, i'd appreciate telling me wrong code , how event target. thanks.
you need pass event object parameter
$(document).ready(function () { $("ul").children().each(function (i) { $(this).click(function (e) { var indexitem = i; if (indexitem == 0) { displayid(e); } if (indexitem == 1) { displaynode(e); } if (indexitem == 2) { displaynodevalue(); } }); }); })
demo: fiddle
also try
$(document).ready(function () { var fns = [displayid, displaynode, displaynodevalue] $("ul").children().click(function (e) { var indexitem = $(this).index(); fns[indexitem] ? fns[indexitem](e) : ''; }); })
demo: fiddle
Comments
Post a Comment