我有一些HTML元素
<p class="accordion-header open" id="platform_0" onclick="validateScreens(this)">Platform 0</p>
<p class="accordion-header open" id="platform_1" onclick="validateScreens(this)">Platform 0</p>
<p class="accordion-header open" id="platform_2" onclick="validateScreens(this)">Platform 0</p>
我想删除并恢复此元素上的click事件。我的JavaScript代码是:
function validateScreens(domObj)
{
if(some condition)
{
$(domObj).off("click"); // //remove click from <p> whenever there is a click event
} else {
$(domObj).on("click",function() { return true; });// restores the click event
}
}
它正在成功删除click事件但没有恢复它。如何去做。
答案 0 :(得分:1)
<p class="accordion-header open" id="platform_0" onclick="validateScreens(this)">Platform 0</p>
<p class="accordion-header open" id="platform_1" onclick="validateScreens(this)">Platform 0</p>
<p class="accordion-header open" id="platform_2" onclick="validateScreens(this)">Platform 0</p>
<script>
function validateScreens(domObj){
if(some condition){
$(domObj).on("click" , function( e ){ e.preventDefault(); });
}else{
$(domObj).on("click",function() { return true; });
}
}</script>
当调用 event.preventDefault 方法时,不会触发事件的默认操作。
答案 1 :(得分:0)
为什么不尝试在事件处理程序本身中进行此检查的不同方法
var allowClick = true;
function validateScreens(domObj) {
if (some condition) {
allowClick = true;
} else {
allowClick = false;
}
}
$(domObj).on("click", function() {
if (allowClick) {
// Do click logic here
}
});
答案 2 :(得分:0)
将其置于相同的If条件下。请尝试这个:
if(some condition)
{
//remove click and restore it
$(domObj).off("click").on("click",function() { return true; });
} else {
// anything else if false
}