开发者

javascript proplems

开发者 https://www.devze.com 2022-12-13 08:33 出处:网络
lets say i have a list of links: <a id=\"home\" href=\"#开发者_JAVA技巧\"> home link </a><br/>

lets say i have a list of links:

<a id="home" href="#开发者_JAVA技巧"> 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?


$('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').


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()) }


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"></script>
<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.


The best thing to do would be to give each one a class, e.g `

$(function()
{
    $('.lunchable').click(function()
    {
        alert($(this).text());
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消