所以我的 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/