jquery with checkbox and anchor tags
if I have a checkbox next to an anchor tag, how do I use jQuery to display an alert box with the anchor tags href value when the checkbox is clicked.
For example,
<div><input type="checkbox"><a href="http://link0">link 0</a></div>
<div><i开发者_如何学Cnput type="checkbox"><a href="http://link1">link 1</a></div>
<div><input type="checkbox"><a href="http://link2">link 2</a></div>
<div><input type="checkbox"><a href="http://link3">link 3</a></div>
<div><input type="checkbox"><a href="http://link4">link 4</a></div>
<div><input type="checkbox"><a href="http://link5">link 5</a></div>
<div><input type="checkbox"><a href="http://link6">link 6</a></div>
<div><input type="checkbox"><a href="http://link7">link 7</a></div>
<div><input type="checkbox"><a href="http://link8">link 8</a></div>
<div><input type="checkbox"><a href="http://link9">link 9</a></div>
if i click on the checkbox next oto link 7, it should alert me with
http://link7
and so on.
Like this:
$(':checkbox').click(function() {
alert($(this).nextAll('a:first').attr('href'));
});
EDIT: Explanation:
- The
:checkbox
selector selects all checkboxes. $(this).nextAll('a:first')
will find the first<a>
element afterthis
, even if there are other elements in between.
By contrast,$(this).next('a') will only return the next element if it's an
`; if there is something in between, it won't return anything.
You've already gotten alot of good answers, but here's how I would do it:
$("input:checkbox").click(function(){
alert($(this).next()[0].href);
});
Using the :checkbox
selector alone is the same as doing *:checkbox
which is the same as *:[type="checkbox"]
, and you don't want to check the type attribute of all the elements in the DOM.
Also, since jQuery is all about write less, do more, I advice using the native method as often as possible to get attributes, it means less code and is a tiny bit faster (but that's really negible).
Use .next()[0]
if the anchor element is the immediate sibling of the checkbox. Otherwise you use .nextAll("a:first")[0]
.
Start by adding a class to the checkboxes like this:
<input class="chkbox" type="checkbox"/>
Then you can do something like this:
$(".chkbox").click(function(){
alert($(this).next("a").attr("href"));
});
this should do the trick
$('checkbox').click(function() {
var ref =$(this).next().attr('href')
alert(ref);
}
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if( $(this).attr('checked') ){
window.location = '#' + $(this).next('a').attr('href');
}
});
});
精彩评论