javascript - How to retrieve id from selected item using "this" -
i new @ jquery/javascript. tried suggestions found on forum far did not help.
this trying:
when loading categories database ( using ajax) html statement added each category:
$("#links ul").append('<li id=\"cat' + + '" data-catid=' + + '>' + categorie_tekst[1] + '</li>'); using f12 see lines correctly added.
e.g. <li id="cat3" data-catid="3">seafood </li>
next step selecting category in screen , retrieve products of category using value set data-catid.
i have been told "this.id" far no luck. displaying value of this.id alert returns correct value reason can't use it.
when add (#cat3).attr(“data-catid”) in code works. different options these did not work:
("#cat"+ this.id).attr(“data-catid”) (this).attr(“data-catid”) var x = $(this).id(); var rest = x.substr(4, 1); everything "this" creates error : uncaught typeerror: ("#cat" + this.id).attr not function...
trying display of these options not give output (not popup when set alert)
any appreciated!
you loading dynamic values. please use event delegation. , $.one() binds event once.
you need add in ready function.
$(document).ready(function () { $("#links ul").one("click", ".cat", function(){ alert($(this).data('catid')) }); }); to ids of elements, use $(this).attr("id") or $(this).prop("id") (latest jquery) instead of this.id, sometimes, might return jquery object.
Comments
Post a Comment