[英]JQuery (“button”).click doesn't work
The example below works. 以下示例有效。 (Example taken from w3cschools, and hacked a bit.) Clicking anywhere in the DIV will cause the address class div to disappear.
(例子来自w3cschools,并且有点被黑了。)点击DIV中的任何地方都会导致地址类div消失。 However, changing the third line of the script to read
但是,更改脚本的第三行要读取
$("button").click(function(){
instead of "div" and it just sits there like a paperweight. 而不是“div”,它只是像纸镇一样坐在那里。 What am I missing.
我错过了什么
<!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>
Change 更改
$(this).children(".address").toggle("slow");
To something like: 对于这样的事情:
$('.address').toggle("slow");
OR 要么
$(this).siblings(".address").toggle("slow");
Once you make the listener act on the button
element, .address
is not a child of button any longer. 一旦你使监听器对
button
元素起作用, .address
就不再是按钮的子.address
了。 It's a sibling. 这是一个兄弟姐妹。 If there will be multiple
.address
classes on your page, you must use siblings. 如果页面上有多个
.address
类,则必须使用兄弟姐妹。
Try this: 尝试这个:
$("button").on("click", function(){
$(this).parent().children(".address").toggle("slow");
});
http://jsfiddle.net/hescano/9S722/ http://jsfiddle.net/hescano/9S722/
$(this).parent().children(".address").toggle("slow");
该按钮没有孩子
$("div").click(function(){
$(this).children(".address").toggle("slow");
});
The meaning of such code above is that, when click trigger in div container, it will go through its children for matching "address" class attribute. 上面这样的代码的含义是,当在div容器中单击触发器时,它将通过其子代码来匹配“address”类属性。
However, if you just change $("div") to $("button"), but no child appears within button element. 但是,如果您只是将$(“div”)更改为$(“button”),但按钮元素中不会显示子项。 nothing matches for toggle function, just ignore it.
没有匹配的切换功能,只需忽略它。
You should change code to as below: 您应该将代码更改为:
$("button").click(function () {
$(this).next(".address").toggle("slow");
});
which find next sibling to button element. 找到按钮元素的下一个兄弟。 That is the element you want.
这是你想要的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.