odoo中有关点击事件的jquery功能不起作用

问题描述

我正在尝试使用下面的jquery代码对我的前视图进行一些动态更改,以使odoo开关像单选按钮一样工作。因此可以一次选择一个单选按钮

注意:console.log(“ test”)在工作,但是带CSS选择器的代码不工作

请指导我如何运行脚本以使其正常运行

 $(document).ready(function(){
        $(".wk_checked_question").click(function(){
            alert("you click me!");
          
        });
        console.log("test");
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
*test.html**

     <tbody>
       <tr>
         <td class="question_id" style="width:70%">Q1.  t-shirt coler 
            size</td>
            <td class="question_id" style="width:50%">$ 120.00</td>
            <td><label class="switch">
            input class="wk_checked_question" data-id="2" type="checkbox">
            <span class="check_box round"></span>
            </label>
          </td>
       </tr>
        <tr>
        <td class="question_id" style="width:70%">Q2.  t-shirt size</td>
        <td class="question_id" style="width:50%"> Free</td>
        <td>
          <label class="switch">
           <input class="wk_checked_question" data-id="1" type="checkbox">
           <span class="check_box round"></span>
          </label>
        </td>
           </tr>
         </tbody>

解决方法

也许这就是您想要的:

$(document).ready(function(){
   $("body").on("click",".wk_checked_question",function(ev){
      $(".wk_checked_question").each((i,cb)=>cb.checked=(cb==this));
      this.checked=true; // a "real" radio button cannot be unchecked ...
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:500px">
 <tbody>
   <tr>
      <td class="question_id" style="width:70%">Q1.  t-shirt color size</td>
      <td class="question_id" style="width:50%">$ 120.00</td>
      <td><label class="switch"><input class="wk_checked_question" data-id="2" type="checkbox">
         <span class="check_box round"></span></label></td>
   </tr>
   <tr>
     <td class="question_id" style="width:70%">Q2.  t-shirt size</td>
     <td class="question_id" style="width:50%"> Free</td>
     <td>
       <label class="switch">
        <input class="wk_checked_question" data-id="1" type="checkbox">
        <span class="check_box round"></span></label></td>
   </tr>
 </tbody>
</table>

在单击复选框后,.each()循环遍历具有相同类的所有复选框,并仅设置与单击的ono(this)相同的复选框。其他所有选项均未选中。

我在@ freedomn-m的注释中建议使用带有jQuery.on()的“委托事件附件”。这样做的好处是,它将可以在事件附加时甚至不存在的目标元素(.wk_checked_question)上工作。

您的HTML还在我添加的<table>周围缺少<tbody>标签。

修改

回到这个答案,我意识到我可以进一步简化脚本,并允许使用以下方法再次取消选择选项:

$("body").on("click",function(ev){
 let newstate=this.checked;
 $(".wk_checked_question").prop("checked",false);
 this.checked=newstate
});

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...