javascript - Jquery 通过单击复选框仅更改一段

标签 javascript jquery html ruby-on-rails

所以我的 Rails 应用程序中有一个复选框和一个段落 -

<li class="task" id="task_<%= task.id %>" >
  <%= check_box_tag task.id, task.id, task.mark, class: "task-check" %>
  <label for=<%=task.id %> ></label>
    <p><%= task.content %></p>

我想通过单击复选框来切换段落的类

我编写了一些 Jquery 函数来更改任务状态(这不是那么重要,但也许您会想知道它)并切换类 -

$(".task-check").on('click', function(){
      $.ajax({
        url: '/tasks/'+this.value+'/mark',
        type: 'POST',
        data: {"mark": this.checked}
      });
      $('p').toggleClass('done')
  });

但是它改变了页面上的所有段落,所以我想念了this,但我不知道应该把this放在哪里

最佳答案

已更新

$(".task-check").on('change', function(){
    // always cache the element, this increase the performance,
    // also in javascript, `this` is too tricky and may change inside blocks
    // so by caching, you can always trust chached item
    var $this = $(this);

    $.ajax({
        url: '/tasks/'+ $this.val() +'/mark',
        type: 'POST',
        data: {"mark": $this.is(':checked') }
    });

    $this.next().toggleClass('done');
    // OR if `p` isn't next item (if so, maybe you should add `class` to p,
    // so you can find that easily)
    // $this.parent().find('p.MY-CLASS').toggleClass('done');
});

关于javascript - Jquery 通过单击复选框仅更改一段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39060763/

相关文章:

javascript - Dc.js 刷机滞后。与 dc.js 版本 1.3 不同,过滤多次

javascript - 使用 angularjs 渲染表格

javascript - observableArray 中可观察值的 knockout 计算

html - CSS - 制作一个 "wall"的 div,它们之间没有空格

javascript - 使用 angularJS Controller 生成下拉菜单

javascript - 计算多种货币格式元素的总和

javascript - 关于 jquery 调整大小插件的建议

jQuery:易于调整的工具提示,无需使用图像,并且免费用于商业用途

jquery - 表单输入焦点问题

javascript - 如何将 MathJax 公式转换为 img