![](/img/trans.png)
[英]Trying to change element behaviour by changing its class. - .on(“Click”)
[英]Change element id and behaviour on click
我需要创建一个按钮,以更改其点击时的ID及其名称。 仅当我第一次单击“开始!”时,它才会更改。 之后,它不起作用,我也不知道为什么。
$("#start").click(function(){
$(this).attr("id", "stop");
$(this).html("Stop!");
});
$("#stop").click(function(){
$(this).attr("id", "start");
$(this).html("Start!");
});
更改ID不是一个好主意。
有一个按钮并切换类和内容
$("#toggle").on("click",function(){ $(this).toggleClass("stop"); $(this).html($(this).is(".stop")?"Stop":"Start"); // if ($(this).is(".stop")) {} else {} });
.stop { background-color:red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="toggle">Start</button>
$('#stop')
选择器无法运行,因为您在运行时没有带id stop
html元素。 因此,您有2个选择:仅使用一个侦听器或使用jQuery的委派系统。
一位听众:
$('#start').click(function() {
var $this = $(this),
id = $this.attr('id');
if (id == 'start') {
$this.attr('id', 'stop');
$this.html('Stop!');
} else {
$this.attr('id', 'start');
$this.html('Start!');
}
});
委派系统:
$(document.body).on('click', "#start", function(){
$(this).attr("id", "stop");
$(this).html("Stop!");
});
$(document.body).on('click', "#stop", function(){
$(this).attr("id", "start");
$(this).html("Start!");
});
无论如何,mplungjan是正确的。 更改ID不是一个好主意。 您应该为此使用CSS类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.