我做了一个代码,其中有一个加号(+)的图像。单击它时,它会旋转,直到旋转 45° (x)。我正在通过 toggleClass
完成它...现在,我有大约 7 张这些图像,但此点击事件仅针对第一个图像运行,为什么?我尝试了 each
函数,但还是一样..完全丢失了...
有 jQuery 的代码:
$("#plus_x").each(function() {
$(this).on("click", function(){
console.log("CLICK!");
$(this).toggleClass("box_rotate box_transition");
$("#item").hasClass("open-panel")
? ($("#item").delay(250).animate({height: '75px'}),
$("#item").removeClass("open-panel"))
: ($("#item").delay(250).animate({height: "300px"}),
$("#item").addClass("open-panel"));
});
});
这是 HTML:
<div id="timeline">
<div id="item" style="border-left: 4px solid #8E44AD;">
<div id="date">
<h1>31. 5.</h1>
</div>
<div id="plus">
<img id="plus_x" src="plus.png" style="">
</div>
</div>
<div id="item">
<div id="date">
<h1>31. 5.</h1>
</div>
<div id="plus">
<img id="plus_x" src="plus.png" style="">
</div>
</div>
<div id="item">
<div id="date">
<h1>31. 5.</h1>
</div>
<div id="plus">
<img id="plus_x" src="plus.png" style="">
</div>
</div>
<div id="item">
<div id="date">
<h1>31. 5.</h1>
</div>
<div id="plus">
<img id="plus_x" src="plus.png" style="">
</div>
</div>
</div>
和CSS..:
#item{
height: 75px;
width: 100%;
background-color: white;
border-bottom: 2px solid #464646;
}
.item_roll{
height: 275px;
}
.box_rotate {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.50+ */
}
.box_transition {
-webkit-transition: all 0.3s ease-out; /* Chrome 1-25, Safari 3.2+ */
-moz-transition: all 0.3s ease-out; /* Firefox 4-15 */
-o-transition: all 0.3s ease-out; /* Opera 10.50–12.00 */
transition: all 0.3s ease-out; /* Chrome 26, Firefox 16+, IE 10+, Opera 12.50+ */
}
#date{
width: 50%;
float: left;
}
#plus{
width: 75px;
height: 75px;
float: right;
padding: 22.5px;
}
希望,您现在有足够的信息来解决我的问题。当然,THERE is link to my website ,所以在页面底部,检查一下,试试看...请帮助我
谢谢
注意!
在 Edge 中看起来很奇怪,不知道为什么....
最佳答案
HTML 中的 id
属性必须具有唯一值,您不能像您那样为不同的元素重复相同的 id
值。
要解决这个问题,请将这些 id="plus_x"
属性替换为 class="plus_x"
并在 上执行您的
选择器。each
$(".plus_x")
但是,对于其他具有值 item
、date
和 plus
的 id
属性,您也有同样的问题,所以你还需要以类似的方式解决这个问题,也在你的 CSS 中。
最后,为了您的目的,没有必要执行each
,因为您可以一次为所有匹配项定义一个点击处理程序。您需要找到属于被点击元素的 .item
,您可以使用 .closest()
来完成:
$(".plus_x").on("click", function(){
console.log("CLICK!");
$(this).toggleClass("box_rotate box_transition");
// get ancestor that has "item" class:
var $item = $(this).closest(".item");
$item.delay(250).animate({
height: $item.hasClass("open-panel") ? '75px' : '300px'
});
$item.toggleClass("open-panel");
});
关于javascript - jQuery .click.each 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36236375/