views:

77

answers:

4

lets say i have a list of links:

<a id="home" href="#"> home link </a><br/>
<a id="list1" href="#"> some text1 </a><br/> 
<a id="list2" href="#"> some text2 </a><br/> 
<a id="list3"> href="#"> some text3 </a><br/> 
<a id="list4" href="#"> some text4 </a><br/
<a id="list5" href="#"> some text5 </a><br/>
<a id="list sails" href="#"> sails link </a><br/>

and if some list link is clicked i get an alert with its text

i wrote a script but it isnt right, it looks like this

function lunch(){
  alert( $(this).text()) }

for

<a id="listn" href="#" onclick="lunch()"> some text5 </a><br/>

how to do this on jquery or just javascript?

+5  A: 
$('a[id^=list]').click(function () {
    alert($(this).text());
});

This will work for all links that has an id starting with 'list'. if you want it to work for all links change the selector to $('a').

RaYell
+1 and voted to delete my own post, you win by 33 seconds :)
JasonWyatt
+1  A: 

You should pass the node instance into the lunch function.

< a id="listn" href="#" onclick="lunch(this)"> some text5 < /a>

And use this as argument

function lunch(node){ alert( $(node).text()) }
nemisj
+1  A: 

Do this:

<div id="links">
<a id="home" href="#">home link</a>
<a id="list1" class="list" href="#">some text1</a>
<a id="list2" class="list" href="#">some text2</a>
<a id="list3" class="list" href="#">some text3</a>
<a id="list4" class="list" href="#">some text4</a>
<a id="list5" class="list" href="#">some text5</a>
</div>

with:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
$(function() {
  $("#links a").click(function() {
    alert(this.id);
    return false;
  });
});
</script>

or to restrict it to just the list ilinks:

$("a.list").click(function() {
  alert(this.id);
  return false;
});

You'll note that I put a class in there instead of using an attribute selector, which generally isn't advised. Also, by the principles of Unobtrusive JavaScript you should add your event handlers this way rather than using onclick attributes.

cletus
+1  A: 
Greg