javascript - JQuery ajax 在具有 2 个单击事件的 2 个按钮类之间更改,但不能更改按钮的值

标签 javascript jquery html css

<分区>

我有一个按钮 <button class="open" id="1">Open</button>

如果我点击按钮,我希望按钮变为 <button class="close" id="1">Close</button>

我为它做了一些脚本

这是脚本:

$(".open").click(function(){
    $ths=$(this);
    var id=$(this).val();
    $.ajax({
        type:"POST",
        url:"someurl",
        dataType: "html",
        data:id,
        success:function(res){
            $thd.html("Open");
            $ths.toggleClass("open close");
        }
    })
});

$(".close").click(function(){
    $ths=$(this);
    var id=$ths.val();
    $.ajax({
        type:"POST",
        url:"someurl",
        dataType: "html",
        data:id,
        success:function(res){
            $ths.html("Close");
            $ths.toggleClass("close open");
        }
    })
});

当我尝试时,第一次点击它改变了 <button class="open" id="1">Open</button>进入<button class="close" id="1">Close</button>

第二次点击我希望它变回这个 <button class="open" id="1">Open</button>

但是并没有变成我想要的样子。变成了这个 <button class="open" id="1">Close</button>它只改变了类,关闭的文本没有打开。

有人可以解释为什么它不起作用吗?以及如何使该按钮更改类及其文本,哦,是的,这个问题也有名字吗?

提前感谢您的回答!

最佳答案

$(".close") 将在 DOM 中找到元素 .close 并绑定(bind)事件。当您动态更改元素的类时,当 jQuery 尝试查找元素时,元素不在 DOM 中。

Use Event Delegation, Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. Use .on() instead of click

$(document).on("click", ".open", function() {
  $ths = $(this);
  var id = $(this).val();
  $.ajax({
    type: "POST",
    url: "someurl",
    dataType: "html",
    data: id,
    success: function(res) {
      $ths.html("Open"); //You had a typo here!
      $ths.toggleClass("open close");
    }
  })
});

$(document).on("click", ".close", function() {
  $ths = $(this);
  var id = $ths.val();
  $.ajax({
    type: "POST",
    url: "someurl",
    dataType: "html",
    data: id,
    success: function(res) {
      $ths.html("Close");
      $ths.toggleClass("close open");
    }
  })
});

关于javascript - JQuery ajax 在具有 2 个单击事件的 2 个按钮类之间更改,但不能更改按钮的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36470422/

相关文章:

javascript - 如何在 contenteditable 区域选择被替换的文本

javascript - Draggabilly 不向新添加的元素添加事件

javascript - 溢出隐藏自动滚动

Jquery hasClass 方法不起作用

javascript - 悬停时如何将背景 gif 放在 <a> 链接中

html - 选择具有特定类的最后一个元素

javascript - 用画外音增加 `role="spinbutton"`

javascript - 从纬度经度获取国家

javascript - 是否可以设置跨域 iframe 内容的样式?

javascript - 如何将类 'active' 添加到 href 在 location.pathname 中的导航项