在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的评论中所建议的CCD_ 3。这样做的优点是,它将处理在事件附件时甚至不存在的目标元素(.wk_checked_question(。

您的HTML也缺少我添加的<tbody>周围的<table>标记。

编辑

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

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

最新更新