簡體   English   中英

JQuery(“按鈕”)。單擊不起作用

[英]JQuery (“button”).click doesn't work

以下示例有效。 (例子來自w3cschools,並且有點被黑了。)點擊DIV中的任何地方都會導致地址類div消失。 但是,更改腳本的第三行要讀取

$("button").click(function(){

而不是“div”,它只是像紙鎮一樣坐在那里。 我錯過了什么


<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("div").click(function(){
    $(this).children(".address").toggle("slow");

  });
});
</script>
<style type="text/css"> 
div.ex
{
background-color:#e5eecc;
padding:7px;
border:solid 1px #c3c3c3;
}
</style>
</head>
<body>

<h3>Island Trading</h3>
<div class=ex>
    <button>Hide me</button>
  <div class=address>
    <p>Contact: Helen Bennett<br> 
    Garden House Crowther Way<br>
    London</p>
  </div>
</div>

<h3>Paris spécialités</h3>
<div class=ex>
<button class="hide">Hide me</button>
<div class=address>
<p>Contact: Marie Bertrand<br> 
265, Boulevard Charonne<br>
Paris</p>
</div>
</div>

</body>
</html>

更改

$(this).children(".address").toggle("slow");

對於這樣的事情:

$('.address').toggle("slow");

要么

$(this).siblings(".address").toggle("slow");

一旦你使監聽器對button元素起作用, .address就不再是按鈕的子.address了。 這是一個兄弟姐妹。 如果頁面上有多個.address類,則必須使用兄弟姐妹。

http://jsfiddle.net/9S722/1/

嘗試這個:

$("button").on("click", function(){
    $(this).parent().children(".address").toggle("slow");
});

http://jsfiddle.net/hescano/9S722/

$(this).parent().children(".address").toggle("slow");

該按鈕沒有孩子

$("div").click(function(){
    $(this).children(".address").toggle("slow");
});

上面這樣的代碼的含義是,當在div容器中單擊觸發器時,它將通過其子代碼來匹配“address”類屬性。

但是,如果您只是將$(“div”)更改為$(“button”),但按鈕元素中不會顯示子項。 沒有匹配的切換功能,只需忽略它。

您應該將代碼更改為:

$("button").click(function () {
    $(this).next(".address").toggle("slow");
});

找到按鈕元素的下一個兄弟。 這是你想要的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM