Jquery html函数第二次无法正常工作

时间:2017-03-01 14:50:38

标签: jquery

我试图在内联样式的输入按钮上强制进行一些更改。我使用jQuery的html函数。当我点击+按钮时它第一次工作,但是当我点击 - 按钮

时它不工作
<div id='div_bouton_moins'><input type=button  value='-' id='bouton_moins' style='background-color:green !important'></div>
<div id='div_bouton_plus'><input type=button  value='+' id='bouton_plus' style='background-color:red !important'></div>


$('#bouton_moins').click(function(){

$('#div_bouton_plus').html("<input type=button  value='+' id='bouton_plus' style='background-color:red !important'>")
$('#div_bouton_moins').html("<input type=button  value='-' id='bouton_plus' style='background-color:green !important'>");
});


$('#bouton_plus').click(function(){

$('#div_bouton_plus').html("<input type=button  value='+' id='bouton_plus' style='background-color:green !important'>");
$('#div_bouton_moins').html("<input type=button  value='-' id='bouton_plus' style='background-color:red !important'>");


});

https://jsfiddle.net/z148xexp/

感谢所有

2 个答案:

答案 0 :(得分:0)

您的问题是:点击后,您可以全新创建按钮。该新按钮不再附加任何onclick事件。

如果您只想更改样式,最简单的方法就是这样:

$('#bouton_plus').click(function(){

    $('#div_bouton_plus').css({"background-color":"green"});
    $('#div_bouton_moins').css({"background-color":"red"});

});

答案 1 :(得分:0)

您需要使用 event delegation ,因此您必须为点击添加的元素绑定一点点不同,您还需要为minus符号按钮添加正确的ID :

&#13;
&#13;
$(document).on('click', '#bouton_moins', function() {
  $('#div_bouton_plus').html("<input type=button  value='+' id='bouton_plus' style='background-color:red !important'>")
  $('#div_bouton_moins').html("<input type=button  value='-' id='bouton_moins' style='background-color:green !important'>");
});

$(document).on('click', '#bouton_plus', function() {
  $('#div_bouton_plus').html("<input type=button  value='+' id='bouton_plus' style='background-color:green !important'>");
  $('#div_bouton_moins').html("<input type=button  value='-' id='bouton_moins' style='background-color:red !important'>");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div_bouton_moins'><input type=button value='-' id='bouton_moins' style='background-color:green !important'></div>
<div id='div_bouton_plus'><input type=button value='+' id='bouton_plus' style='background-color:red !important'></div>
&#13;
&#13;
&#13;

你这样过于复杂。如果您没有被其他一些事情强迫,请尝试添加和删除.active课程:

&#13;
&#13;
$('input[type="button"]').click(function() {
  $('.active').removeClass('active');
  $(this).addClass('active');
});
&#13;
input[type="button"] {
  background: red;
}

input[type="button"].active {
  background: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div_bouton_moins'><input type=button value='-' class='active' id='bouton_moins'></div>
<div id='div_bouton_plus'><input type=button value='+' id='bouton_plus'></div>
&#13;
&#13;
&#13;

相关问题