首页 > 编程知识 正文

jquery禁止点击事件,javascript点击事件失效

时间:2023-05-06 07:03:11 阅读:260937 作者:3614

关于jquery的点击事件的比较,发现在某种情况下点击事件不管用了;将使用三种点击触发事件进行比较,可以看出一些端倪,对于开发者而言,想必是十分有用的;


chenglin博客,原文链接:http://www.chenglin.name/web/js-web/484.html


我们将用到三种点击触发事件来比较,分别是:


$('').click(function(){}); // 指定对象

$(document).on('click','',function(){}); // 获取整个网页文档对象来指定

function a_test_func(){}; // 调用函数

这里我将写出两个a标签来完成数据点击的测试,网页效果如下:


<a rel="external nofollow" href="http://www.chenglin.name/wp-content/uploads/2014/02/1.png"><img src="http://www.chenglin.name/wp-content/uploads/2014/02/1.png" alt="1" width="323" height="146" class="alignnone size-full wp-p_w_picpath-485" /></a>

可以看到两个a标签,一个名字为 a_test,一个为a_add.分别代表一下意思:


a_test:默认在网页中直接写一个a标签

a_add: 使用js函数在a_test后面追加一个a标签名为a_add;

a_test直接写入网页,a_add由函数追加的代码,他们两个都有一个class为a_test;代码如下:


<a class="a_test" rel="external nofollow" rel="external nofollow" href="#" οnclick="a_test_func()">a_test</a>


<script type="text/javascript">

$('.a_test').click(function(){

console.log('jquery');

});

// 获取整个网页文档对象

$(document).on('click','.a_test',function(){

console.log('document');

});

// 函数

function a_test_func(){

console.log('********************');

console.log('function');

}


function a_add(){

$('.a_test').after('<a class="a_test" rel="external nofollow" rel="external nofollow" href="#" οnclick="a_test_func()">a_add</a>');

}

a_add();

</script>

我将从console输出来查看两个a标签点击的结果,首先看没有点击的时候:

原文链接:http://www.chenglin.name/web/js-web/484.html

点击第一个a标签,这个是直接写入网页的:

原文链接:http://www.chenglin.name/web/js-web/484.html

点击第二个a标签,这个是代码追加的:

原文链接:http://www.chenglin.name/web/js-web/484.html

可以看到差异了吧,发现追加的第二个a标签,没有输出:


$('').click(function(){}); // 指定对象的点击结果 jquery

这样可以得出结论,关于网页追加的代码,是不能使用


$('').click(function(){}); // 指定对象的

总结一下,推测上面这个监听函数,是在网页加载的时候就指定了对象,而通过代码追加,如json追加,的元素,是不能在匹配这个事件的。

以后可以统一使用,以下的方法来避免,失效的问题:


$(document).on('click','',function(){}); // 获取整个网页文档对象来指定

function a_test_func(){}; // 调用函数

对于这个两个方法,是元素在点击事件后才进行处理,所有使用后面两种方法,可以避免点击事件在一些未知的情况下失效…….大家可以拷贝上面的代码,指定jquery试一下~~


chenglin博客,原文链接:http://www.chenglin.name/web/js-web/484.html


转载于:https://blog.51cto.com/xddesign/1621964

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。