Javascript 单击更改元素id和行为
我需要制作一个按钮,在单击时更改其id和名称。只有当我第一次点击“开始”时,它才会改变。在那之后它就不起作用了,我不知道为什么Javascript 单击更改元素id和行为,javascript,jquery,Javascript,Jquery,我需要制作一个按钮,在单击时更改其id和名称。只有当我第一次点击“开始”时,它才会改变。在那之后它就不起作用了,我不知道为什么 $("#start").click(function(){ $(this).attr("id", "stop"); $(this).html("Stop!"); }); $("#stop").click(function(){ $(this).attr("id", "start"); $(this).html("Start!"); }); 更改ID不
$("#start").click(function(){
$(this).attr("id", "stop");
$(this).html("Stop!");
});
$("#stop").click(function(){
$(this).attr("id", "start");
$(this).html("Start!");
});
更改ID不是一个好主意 有一个按钮并切换类和内容
$(“#切换”)。打开(“单击”,函数(){
$(this.toggleClass(“停止”);
$(this.html($(this.is(“.stop”)?“stop”:“Start”);//if($(this.is(.stop)){}else{}
});代码>
.stop{背景色:红色}
开始更改ID不是一个好主意
有一个按钮并切换类和内容
$(“#切换”)。打开(“单击”,函数(){
$(this.toggleClass(“停止”);
$(this.html($(this.is(“.stop”)?“stop”:“Start”);//if($(this.is(.stop)){}else{}
});代码>
.stop{背景色:红色}
启动
运行
$(“#停止”)
选择器时,由于没有id为
停止的html元素,因此该选择器无法工作。因此您有两种选择:只使用一个侦听器或使用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!");
});
无论如何,姆普隆詹是对的。更改ID不是一个好主意。为此,您应该使用CSS类。运行时,$(“#stop”)
选择器无法工作,因为您没有id为stop
的html元素。因此您有两种选择:只使用一个侦听器或使用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!");
});
无论如何,姆普隆詹是对的。更改ID不是一个好主意。你应该使用CSS类来实现这一点。Try.prop()函数。Try.prop()函数。我同意-我是对的:))我怀疑示例1在没有示例2的情况下能否工作我同意-我是对的:))我怀疑示例1在没有示例2的情况下能否工作