单击时更改元素ID和行为

时间:2015-07-06 11:17:42

标签: javascript jquery

我需要创建一个按钮,在点击时更改其ID及其名称。只有当我第一次点击“开始!”时它才会改变。之后它不起作用,我不知道为什么。

$("#start").click(function(){
  $(this).attr("id", "stop");
  $(this).html("Stop!");
});

$("#stop").click(function(){
  $(this).attr("id", "start");
  $(this).html("Start!");
});

2 个答案:

答案 0 :(得分:4)

更改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>

答案 1 :(得分:2)

$('#stop')选择器不起作用,因为您在运行时没有标识为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!");
});

无论如何,mplungjan是对的。更改ID不是一个好主意。你应该使用CSS类。

相关问题