5

as the title says I'm trying to disable OnClick for specific

<div id="test" style="display: block; opacity: 0.89;"></div>

this div is loaded from external script which is obfuscated so i cannot see the specific code.

What I have tried to remove this

$("#test").click(function(){ return false});
$("#test").unbind();
$("#test").removeAttr("onclick");
//Suggestions which do not work
$('#test').on('click', function(e) {e.preventDefault();return false;});
$("#test").click(function(event){
event.preventDefault();
});

None of the above work.

EDIT: Solved my problem using .unbind("click"); after the div was created.

4

7 回答 7

14

你可以加off("click");

小提琴

$(function () {
    $("#test").click(function(){alert('test');});
    $("#test").off('click');

});

此代码将演示删除以前添加的单击事件。

于 2013-10-11T14:12:52.463 回答
8

简单的形式,结合 jquery 和 javascript。

// To disable:    

$('#test').each(function (){
    this.style.pointerEvents = 'none'; 
}); 

// To re-enable:
$('#test').each(function (){
    this.style.pointerEvents = 'auto'; 
}); 

因此,您可以更改多个标签的选择器

于 2016-06-10T10:16:22.723 回答
6

如果您在将 div 添加到页面之前使用它们,您尝试过的任何选项都不会起作用。因此,请务必将您的代码放在创建 div 的其他脚本之后的某个位置。

如果多个元素具有相同的 id,那也是一个问题。

关于您尝试过的各个方法:

$("#test").click(function(){ return false});
$("#test").unbind();
$("#test").removeAttr("onclick");

第一行将向元素添加一个的单击处理程序,以防止默认行为并停止事件向上传播,但它不会阻止绑定到该元素的其他事件处理程序运行 - 特别是如果它们在您的新处理程序之前运行,显然.

第二行将删除使用 jQuery 附加的事件处理程序,但不会删除通过其他方式附加的处理程序。

第三行应该可以删除内联onclick属性(如果存在),但不能删除使用 jQuery 添加的处理程序。

假设即使在将 div 添加到页面后确保代码运行后您仍然无法停止点击行为,您可以尝试以下操作:

var $test = $("#test").removeAttr("onclick"),
    $contents = $test.contents().detach();
$test.replaceWith($test.clone(false).append($contents));

演示:http: //jsfiddle.net/A9tmu/3/

这里的想法是用它自己的克隆替换元素,因为克隆版本(当创建时.clone(false))不会保留事件处理程序。我在克隆之前暂时分离了 div 的内容,以便任何子元素都可以保留它们的事件处理程序。

于 2013-10-11T14:27:17.033 回答
0
$('#test').on('click', function(e) {e.preventDefault();return false;});
于 2013-10-11T14:09:29.157 回答
0

您可以unbind单击事件进入click事件:

 $("#test").click(function(){
        $( "#test" ).unbind( "click");
        alert('Jquery/Javascript Event');
    });

试试 JsFiddle

于 2013-10-11T14:21:43.293 回答
0

尝试这个:

$("#test").click(function(event) {
    event.preventDefault();
});
于 2013-10-11T14:09:30.613 回答
0

尝试这个?

$('#test').unbind('click')

或者

   $( "#test" ).bind( "click", handler );
   $( "#test" ).unbind( "click", handler );

尝试这个

$( "#test" ).on("click", function () {
  });
$("#test").off("click");
于 2013-10-11T14:10:03.193 回答