【问题标题】:Jquery change only one paragraph by clicking the chekboxJquery通过单击复选框仅更改一个段落
【发布时间】:2016-08-21 04:08:11
【问题描述】:

所以我的 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放在哪里

【问题讨论】:

    标签: javascript jquery html ruby-on-rails


    【解决方案1】:

    更新

    $(".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');
    });
    

    【讨论】:

    • @Mikhah 现在呢?
    • 类“完成”现在添加到复选框,但不添加到段落
    • 你修改的代码和我的一模一样吗?你能分享渲染的html吗?
    • 所以,在我的回答中使用注释方式$this.parent().find('p').toggleClass('done');
    【解决方案2】:
    $(".task-check").on('click', function(){
      $(this).next('p').toggleClass('done');
    });
    

    为什么叫ajax?如果你需要切换类,你不需要调用ajax

    【讨论】:

      【解决方案3】:

      您需要将事件与 DOM 元素分开。 event是触发器,DOM元素有自己的属性

      var A = window,
          B = document,
          a = function(a){return B.getElementById(a);};
          
      a('checkbox').onclick = function(){
        if(this.checked === true){
          a('parag').setAttribute('class','b');
        } else {
          a('parag').setAttribute('class','a');
        }
      };
      .a{color:#000;}
      .b{color:blue;}
      <p id="parag" class="a">This is paragraph</p><br />
      
      checkbox: <input id="checkbox" type="checkbox"/>

      【讨论】:

        【解决方案4】:

        你可以试试这个。 如果你需要ajax 调用ajax。 你是在 html 之上调用 jQuery 吗?

        $(".task-check").on('change', function(){
          if($(this).is(':checked')){
            $(this).next('p').addClass('done');
          }else{
            $(this).next('p').removeClass('done');
          }
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-04-11
          • 2023-03-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-25
          • 2013-09-17
          相关资源
          最近更新 更多