如何使用jquery在html中添加和选择元素

米拉德

我有一行,我想将数据发送到另一个页面,同时单击“添加”按钮。然后我想删除“添加”类并添加“删除”类,如果我点击“删除”,则再次删除它并添加“添加”类。我的代码在下面,但它不能正常工作

$(function() {
  //selecting a class that contains "btn" and "add" class
  $('.btn.add').click(function() {
    $(this).text("remove");
    $(this).addClass("remove");
    $(this).removeClass("add");
    var $row = $(this).closest("tr"),
      $name = $row.find("td:nth-child(2)"),
      $id = $row.find("td:nth-child(1)");
    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: 'feed.php',
      data: {
        meal: $name.text(),
        day: $id.text()
      },
      success: function(msg) {
        $row.css({
          'background-color': 'rgba(76, 175, 80, 0.3)'
        });
      }
    });
  });
  //selecting a class that contains "btn" and "add" class
  $('.btn.remove').click(function() {
    $(this).removeClass("remove");
    $(this).addClass("remove");
    $(this).text("add");
    var $row = $(this).closest("tr"),
      $name = $row.find("td:nth-child(2)"),
      $id = $row.find("td:nth-child(1)");
    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: 'feed.php',
      data: {
        meal: $name.text(),
        day: $id.text()
      },
      success: function(msg) {
        $('#note').html(msg.aaa + ' ' + msg.bbb + ' ' + msg.ccc);
        $row.css({
          'background-color': 'rgba(255, 0, 0, 0.3'
        });
      }
    });
  });

});
罗希特·夏尔马

实际上,我无法理解您的主要问题,但是您的代码可以缩小如下,无需仅出于类的原因再次重复您的代码。

 $('.btn').click(function(){
    // to change the text
    if($(this).text().trim() === 'add') {
        $(this).text('remove')
    } else {
        $(this).text('add')
    }

    // to change the class name
    if($(this).hasClass('add')) {
        $(this).addClass('remove').removeClass('add')
    } else {
        $(this).addClass('add').removeClass('remove')
    }
    // further code here conditionally
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用jQuery从html元素中添加或删除类

如何使用 jQuery 在 html 元素中添加对象值?

如何使用JQuery从HTML中选择元素

使用jQuery在HTML中添加列表元素

jQuery如何使用add()将元素添加到缓存在变量中的选择中

在jquery中使用.html(value To show)时如何在td元素中添加span元素

如何在Laravel元素形式中添加HTML选择框

添加使用Jquery和Materialize CSS在HTML中选择的选项在Laravel Blade中不起作用

如何使用JQuery在选择元素中设置选择的选项?

如何使用jQuery中的prepend()方法获取添加到html <ul>元素中的html <li>元素的id值?

jQuery使用嵌套div添加和删除HTML元素

如何使用jQuery的nextAll()选择器更改HTML表相邻行中的元素类

如何使用JQuery查找HTML元素的正确选择器

如何在Phantomjs中使用jQuery选择html元素?

如何使用jQuery获取html选择元素的特定值

如何使用jQuery将数组的每个项目添加到单独的HTML元素中?

使用jquery选择html表中输入元素的值

如何在此jQuery中添加HTML元素?

使用JQuery中的数组添加和删除表的元素

在HTML和JQuery上选择子元素

使用JS / Jquery在现有HTML元素中添加图像

如何使用给定的jQuery选择中的元素生成对象

如何使用 JavaScript 选择“this”元素(不在 jQuery 中)

如何在Jquery和html5中使用相同的类管理不同的元素

jQuery:使用jquery动态添加html元素

如何使用jQuery onchange事件在HTML中添加和删除属性?

如何使用 JQuery 在列表中添加元素

如何使用 Js 在 HTML BODY 中插入一个元素,然后使用 Js 选择相同的元素,然后向其中添加更多数据?

从html和javascript中删除选择元素