c#:按钮点击事件–问题记录

itlao6 原创 开发&源码 .NET评论603字数 1101阅读3分40秒阅读模式

上个迭代别人的代码,然后这个迭代我领了相关任务,然后被迫来填坑:

c#:按钮点击事件–问题记录
c#
  • 问题1:

点击事件触发正常,但是看Console中打印出错误日志:Uncaught SyntaxError: Unexpected token )
解决:
javascript:void(0)写成了javascript:void(),少了参数0文章源自IT老刘-https://itlao6.com/969.html

  • 问题2:

按钮点击事件重复
解决:
增加节流函数,如下代码文章源自IT老刘-https://itlao6.com/969.html

    /**
     * 防止重复点击的函数
     * handler 真实需要执行的函数
     * wait 多久内不能重复点击(毫秒ms)
     */
    function throttle(handler, wait) {
        if (!handler.timeoutId) {
            handler.timeoutId = window.setTimeout(function () {
                handler.timeoutId = null;
            }, wait);
            handler(); // 实际点击时间方法
        }
    }

需要使用的地方,设置点击事件 onclick="return throttle(submitClick,500);" 即可,submitClick即为你的实际点击事件,500即500ms触发一次:文章源自IT老刘-https://itlao6.com/969.html

当然,这个节流方法也可以这样写:文章源自IT老刘-https://itlao6.com/969.html

    /**
     * 防止重复点击的函数
     * handler 真实需要执行的函数
     * wait 多久内不能重复点击(毫秒ms)
     */
    function throttle(handler, wait) {
        if (handler.timeoutId) {
            window.clearTimeout(handler.timeoutId)
        }
        handler.timeoutId = window.setTimeout(function () {
            handler();
            handler.timeoutId = null;
        }, wait);
    }

两者的区别是:第一种是先执行handler函数,然后倒计时wait毫秒后才能继续执行;第二种是点击事件触发后,倒计时wait毫秒后才执行handler函数,如果这段时间内有第二次点击事件进入,则移除上一次点击事件,重新开始倒计时,直到wait毫秒内没有点击事件才会最终触发。
这两种没什么孰优孰劣,视具体情况使用即可。文章源自IT老刘-https://itlao6.com/969.html


ps:之所以写这个是因为同事之前写的代码存在问题,防止重复点击如下面这样写:文章源自IT老刘-https://itlao6.com/969.html

    function submitClick() {
        if (!flag) {
            flag= true
            ...实际点击事件触发的代码
            flag= false
        }
    }

这实际上就一个防止并发的代码吧...如何能起到防止重复点击的作用呢?而且html中js也是单线程事件循环,这个有点多余了。文章源自IT老刘-https://itlao6.com/969.html

简书:ThinkinLiu 博客: IT老五文章源自IT老刘-https://itlao6.com/969.html


c#:按钮点击事件–问题记录
IT老五(it-lao5):关注公众号,一起源创,一起学习!
文章源自IT老刘-https://itlao6.com/969.html文章源自IT老刘-https://itlao6.com/969.html
继续阅读
weinxin
我的微信公众号
微信扫一扫关注公众号,不定时更新
itlao6
  • 本文由 发表于 2019年 7月 3日 09:23:07
  • 转载请务必保留本文链接:https://itlao6.com/969.html
评论  0  访客  0
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定