[英]jquery with checkbox and anchor tags
如果我在锚标记旁边有一个复选框,当单击该复选框时,如何使用jQuery显示带有锚标记href值的警报框。
例如,
<div><input type="checkbox"><a href="http://link0">link 0</a></div>
<div><input 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>
如果我单击oto链接7旁边的复选框,它应该警告我
http://link7
等等。
像这样:
$(':checkbox').click(function() {
alert($(this).nextAll('a:first').attr('href'));
});
编辑 :说明:
:checkbox
选择器选择所有复选框。 $(this).nextAll('a:first')
将在this
之后找到第一个<a>
元素,即使它们之间还有其他元素也是如此。 $(this).next('a') will only return the next element if it's an
`; $(this).next('a') will only return the next element if it's an
。 如果介于两者之间,则不会返回任何内容。 您已经获得了很多好的答案,但是这是我的处理方法:
$("input:checkbox").click(function(){
alert($(this).next()[0].href);
});
单独使用:checkbox
选择器与*:checkbox
相同,与*:[type="checkbox"]
,并且您不想检查DOM中所有元素的type属性。
另外,由于jQuery的目的在于减少写,做更多 ,我建议尽可能多地使用本机方法来获取属性,这意味着更少的代码并且速度更快(但这是可以忽略的)。
如果锚元素是复选框的直接同级,则使用.next()[0]
。 否则,请使用.nextAll("a:first")[0]
。
首先将一个类添加到如下复选框:
<input class="chkbox" type="checkbox"/>
然后,您可以执行以下操作:
$(".chkbox").click(function(){
alert($(this).next("a").attr("href"));
});
这应该可以解决问题
$('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');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.