我有以下代码:
<div class="row">
<div class="image">
<div class="slider-img" style="background-image: url('<?php echo site_url('assets/imagens/gama-doce-slider.png') ?>');"></div>
<div class="bottom-buttons">
<span class="see-package">See Package</span>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// First part, change background to the package image and change the text
$(".see-package").click(function() {
$(".slider-img").css("background-image", "url(../assets/imagens/embalagem-teste.jpg)");
$(this).addClass( "see-product" );
$(this).removeClass( "see-package" );
$(this).text( "See Product" );
});
// Second part, adding back the 'see package' and changing background to original
$(".image .bottom-buttons").on("click", ".see-product", function(event){
$(".slider-img").css("background-image", "url(../assets/imagens/gama-doce-slider.png)");
$(this).addClass( "see-package" );
$(this).removeClass( "see-product" );
$(this).text( "See Package" );
});
});
</script>
这样做的目的是能够更改.slider-img的背景和跨度的文本,以便用户可以在“查看包”和“查看产品”之间进行切换。
jquery代码的第二部分基于我在这个帖子中读到的内容: Event binding on dynamically created elements?
我做错了什么?
答案 0 :(得分:1)
第一个事件侦听器直接附加到元素。当你改变它的类时,监听器仍在那里,监听点击。因此,当您将类更改为see-product
并单击它时,将触发两个侦听器。
您可以通过以与第二个侦听器类似的方式附加第一个侦听器来修改此行为:
$(document).ready(function(){
// First part, change background to the package image and change the text
$(".image .bottom-buttons").on("click", ".see-package", function(event){
$(".slider-img").css("background-image", "url(../assets/imagens/embalagem-teste.jpg)");
$(this).addClass( "see-product" );
$(this).removeClass( "see-package" );
$(this).text( "See Product" );
});
// Second part, adding back the 'see package' and changing background to original
$(".image .bottom-buttons").on("click", ".see-product", function(event){
$(".slider-img").css("background-image", "url(../assets/imagens/gama-doce-slider.png)");
$(this).addClass( "see-package" );
$(this).removeClass( "see-product" );
$(this).text( "See Package" );
});
});