jquery - How to get the text from a specific closest element? -
i've been learning code own , fancy stuff jquery library i'm stuck here. got:
<span class='ccy'>san diego</span><span class='dc'> x</span> <span class='ccy'>san francisco</span><span class='dc'> x</span> <span class='ccy'>palo alto</span><span class='dc'> x</span>
i want able click in $("span.dc") , text() of < span> next (the name of city), works fine if there 1 city in html, long keep adding them result gets messy , end string containing city names , need one.
i know obvious thing give them different id each 1 it'd messier 'cause html dynamically generated depending on previous event triggered user, cities come array , need individual name of city delete if 'x' clicked, hope i've explained myself enough.
jsfiddle here!! can see better mean
with markup, simplest use of .prev
$(function() { $(".dc").on("click",function() { var city = $(this).prev().text(); console.log(city); $("#msg").html("you clicked "+city); }); });
.dc { padding-right:3px;border-right:1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <span class='ccy'>san diego</span><span class='dc'> x</span> <span class='ccy'>san francisco</span><span class='dc'> x</span> <span class='ccy'>palo alto</span><span class='dc'> x</span> <br/><span id="msg"></span>
Comments
Post a Comment