2011-01-07 29 views
1

如果我有一個定位標記旁邊的複選框,當單擊該複選框時如何使用jQuery顯示具有定位標記href值的警告框。帶有複選框和定位標記的jquery

例如,

<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 

等。

+2

一個無關的建議:'`元素應該關閉。 – 2011-01-07 15:38:16

回答

5

像這樣:

$(':checkbox').click(function() { 
    alert($(this).nextAll('a:first').attr('href')); 
}); 

編輯:說明:

  • :checkbox selector選擇所有複選框。
  • $(this).nextAll('a:first')將在this之後找到第一個<a>元素,即使其間存在其他元素也是如此。
    相反,$(this).next('a') will only return the next element if it's an`;如果中間有什麼東西,它不會返回任何東西。
+0

爲什麼這比使用Vincent Ramdhanie的建議更好? – oshirowanen 2011-01-07 15:40:44

+1

做'nextAll('a:first')'的目的是什麼?你不能只做'下一個('a')'嗎? – JasCav 2011-01-07 15:43:01

1

開始通過添加一個類的複選框這樣的:

<input class="chkbox" type="checkbox"/> 

然後,你可以做這樣的事情:

$(".chkbox").click(function(){ 
     alert($(this).next("a").attr("href")); 
    }); 
0

這應該做的伎倆

$('checkbox').click(function() { 
    var ref =$(this).next().attr('href') 
    alert(ref); 
    } 
0
$(document).ready(function(){ 
    $('input[type="checkbox"]').click(function(){ 
     if($(this).attr('checked')){ 
      window.location = '#' + $(this).next('a').attr('href'); 
     } 
    }); 

}); 
2

你已經得到了很多很好的答案,但這裏是我會怎麼做:

$("input:checkbox").click(function(){ 
    alert($(this).next()[0].href); 
}); 

單獨使用:checkbox選擇是一樣的做*:checkbox這是一樣的*:[type="checkbox"],和你不想要檢查DOM中所有元素的類型屬性。另外,由於jQuery全部是關於寫少,多做,我建議儘量使用本機方法來獲取屬性,這意味着更少的代碼,並且速度稍微快一些(但這實際上是可以忽略不計的)。如果錨元素是複選框的直接兄弟,則使用.next()[0]。否則,您使用.nextAll("a:first")[0]