社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Jquery

jquery不能添加类或删除类

hayumi kuran • 5 年前 • 188 次点击  

我在Laravel中使用Vuejs,在Watch操作中使用jQuery。

我有noidea为什么hasClass工作,但addClass、removeClass和toggleClass不工作。

这是我的HTML代码:

$('#todo input[type=checkbox]:not(:checked)').each(function(i, elem) {
  var p = $(elem).parent().find('p');
  if (p.hasClass("checked")) {
    p.removeClass("checked");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-check d-flex flex-row pl-2 b-bottom">
  <input type="checkbox" id="sec1To0_chk_msk01" v-model="data.sec1To0_chk_msk01" class="d-none form-check-input" v-if="allow_staff" />
  <label for="sec1To0_chk_msk01" class="form-check-label d-flex pt-2">
        <div class="radio-check d-flex justify-content-center align-items-center">
          <span class="ni ni-check"></span>
        </div>
      </label>
  <p v-bind:class="{ checked:checked }" class="w-100 p-1 m-0">Title</p>
</div>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38136
 
188 次点击  
文章 [ 1 ]  |  最新文章 5 年前
errand
Reply   •   1 楼
errand    6 年前

我不确定,你说的“它不起作用”是什么意思。所以我猜这个问题并提供一个可能的解决方案…

实际上,它是有效的。但是-您的JS片段只执行一次, 页面加载时 /准备好了。我想,你想要你的 <p> 要切换类的元素 checked 每当复选框被选中或取消选中时。 为此,需要将事件触发器绑定到复选框,这样每次执行JS时,都要选中/取消选中该框。

这样做:

//function to execute on every click event of a checkbox
$("input[type=checkbox]").on("click", function(){       
    //instead of using .parent().find() you can simply use .siblings() to find the p element
    myTextElem = $(this).siblings("p");  

    // toggle the class
    myTextElem.toggleClass("checked");

    if(myTextElem.hasClass("checked")){
      // here you can do something, if it is checked
    } else {
      // here you can do something, if it is unchecked
    }
});

当然,只有当选中的类和复选框状态处于某种同步状态时,这才有效。因此,使用click函数,实际上, p 元素将不具有选中的类onload,即使默认选中了复选框。 为此,您需要添加一些代码,以便在DOM上执行:

$("input[type=checkbox]").each(function(){ //loop through all checkboxes
  myTextElem = $(this).siblings("p"); //select sibling text elem
  if($(this).is(":checked")){ //if checkbox is checked
    myTextElem.addClass("checked"); //initially add class checked
  }
});