[英]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.