GVKun编程网logo

javascript – 在JQuery中防止多次点击(jquery防止重复点击)

16

如果您想了解javascript–在JQuery中防止多次点击和jquery防止重复点击的知识,那么本篇文章将是您的不二之选。我们将深入剖析javascript–在JQuery中防止多次点击的各个方面

如果您想了解javascript – 在JQuery中防止多次点击jquery防止重复点击的知识,那么本篇文章将是您的不二之选。我们将深入剖析javascript – 在JQuery中防止多次点击的各个方面,并为您解答jquery防止重复点击的疑在这篇文章中,我们将为您介绍javascript – 在JQuery中防止多次点击的相关知识,同时也会详细的解释jquery防止重复点击的运用方法,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

javascript – 在JQuery中防止多次点击(jquery防止重复点击)

javascript – 在JQuery中防止多次点击(jquery防止重复点击)

我正在创建一个动态测验,我需要防止多次点击我的“下一个”按钮.在点击功能中,我尝试了if条件以防止多次点击.不知道为什么它不起作用.非常感谢一些帮助.

var nextButton= $('<button/>', {
    text: 'Next', 
    id: 'nextButton',
    click: function (event) {
        event.preventDefault();

        if($("#container").filter(':animated').length>0) {
                  return false;
            }

        /* rest of code*/
     }
});

Here是我的应用程序JSfiddle出现的代码

奖金问题:我被告知event.preventDefault()是一个很好的做法.这是真的?如果是这样,为什么?

更新:JSfiddle行#,其中上面的代码是第81行,以防你想要乱用代码而不需要全部挖掘它.

解决方法:

var nextButton= $('<button/>', {
    text: 'Next', 
    id: 'nextButton',
    click: function (event) {
        event.preventDefault();

        if($("#insideContainer").filter(':animated').length>0) {
                  return false;
            }

        /* rest of code*/

     }
});

我发现了原因.你正在检查错误的元素.它应该是#insideContainer
Demo

javascript - 在jQuery中遍历二维数组

javascript - 在jQuery中遍历二维数组

html:

登录后复制
登录后复制

sss表示区域,当点击checkbox时生成session,像这样:$_SESSION [$sss] [$aa]。
要求是:页面刷新时,所勾选的项,仍被勾选。
我知道可以给checkbox设id,根据id设置默认被勾选。也成功了,但主要是我想知道,在a区或b区,他勾选了多少个。所以我使用二维数组。

现在的问题是在jQuery中怎么找到这个checkbox?

这是我用id设置默认被勾选的jQuery和CI框架下的控制器。

jQuery:

var checks=$(''input:checkbox'');
for(var i=0;i<checks.length><p>CI:</p>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f"rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p>
<pre>public function is_session(){
    //当点击选项时 将所属id传过来
    $checked=$this-&gt;input-&gt;post(''checkid'');
    //$area=$this-&gt;input-&gt;post(''area'');
    //判断$_SESSION[$checked],若存在返回$checked(id)
    if(!empty($_SESSION[$checked])){
        echo $checked;
    }
}
登录后复制
登录后复制

谢谢你的帮助。

回复内容:

html:

登录后复制
登录后复制

sss表示区域,当点击checkbox时生成session,像这样:$_SESSION [$sss] [$aa]。
要求是:页面刷新时,所勾选的项,仍被勾选。
我知道可以给checkbox设id,根据id设置默认被勾选。也成功了,但主要是我想知道,在a区或b区,他勾选了多少个。所以我使用二维数组。

现在的问题是在jQuery中怎么找到这个checkbox?

这是我用id设置默认被勾选的jQuery和CI框架下的控制器。

jQuery:

var checks=$(''input:checkbox'');
for(var i=0;i<checks.length><p>CI:</p>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f"rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p>
<pre>public function is_session(){
    //当点击选项时 将所属id传过来
    $checked=$this-&gt;input-&gt;post(''checkid'');
    //$area=$this-&gt;input-&gt;post(''area'');
    //判断$_SESSION[$checked],若存在返回$checked(id)
    if(!empty($_SESSION[$checked])){
        echo $checked;
    }
}
登录后复制
登录后复制

谢谢你的帮助。

感觉你思路不对
推荐你一个方法
$(obj).load("url #局部刷新id");
用jquery 局部刷新,在循环的时候就把对应的属性附上

javascript – Jquery Ajax表单需要2次点击提交

javascript – Jquery Ajax表单需要2次点击提交

我有一个html表单,它执行jquery / ajax验证.

以下是html表格……

<divhttps://www.jb51.cc/tag/Box/" target="_blank">Box3">
    <form method="post" name="loginform" action="models/login.PHP">
    <h2>LOGIN<br /><br /> (Post/Manage Property)</h2>
        <input type="email"name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />
        <divid ="errormsg6"></div>
        <input type="password"name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />
        <divid ="errormsg7"></div>
        <input type="submit" name="login" id="login" value="Submit">
        <divid ="errormsg8"></div>
        <div><a href="forgot-password">Forgot Password</a></div>
    </form>
</div>

用于验证的jquery / ajax如下

$(document).ready(function()
{
    /* ----------------- Login Validations Global Variables -----------------   */
    var user_email2 = "";
    var user_password2 = "";
    var user_emailajax2 = "";
    var user_mobileajax2 = "";

    var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);

    /* ----------------- Define Validate Email */
    var validate_email_login = function()
        {
            var item5 = $("#user_email2").val();
            var item5 = item5.toLowerCase();

            if (item5.length < 6 || item5.length > 50)
            {
                $("#errormsg6").html("Email : 6 - 50 Characters");
                user_email2 = "";
            }
            else
            {
                $("#errormsg6").html("")
                user_email2 = item5;
                if (!emailformat.test(item5))
                {
                    $("#errormsg6").html("Wrong Email Format")
                    user_email2 = "";
                }
                else
                {
                    $("#errormsg6").html("")
                    user_email2 = item5;
                    $.ajax(
                    {
                        type: 'POST',
                        url: 'classes/validatelogin.PHP?f=1',
                        data: "user_email2=" + item5,
                        success: function(msg)
                        {
                            if (msg == "exists")
                            {
                                $("#errormsg6").html("");
                                user_emailajax2 = item5;
                            }
                            else if (msg == "ok")
                            {
                                $("#errormsg6").html("Email Does Not Exist");
                                user_emailajax2 = "";
                            }
                        }
                    });
                }
            }
        }

    /* ----------------- Define Validate Password */
    var validate_password_login = function()
        {
            var item5 = $("#user_email2").val();
            var item5 = item5.toLowerCase();

            var item6 = $("#user_password2").val();
            if (item6.length < 8 || item6.length > 20)
            {
                $("#errormsg7").html("Password : 8-20 Characters")
                user_password2 = "";
            }
            else
            {
                $("#errormsg7").html("")
                user_password2 = item6;
                $.ajax(
                {
                    method: "POST",
                    url: "classes/validatelogin.PHP?f=2",
                    data: "user_email2=" + item5 + "&user_password2=" + item6,
                    success: function(msg)
                    {
                        if (msg == "WrongPw")
                        {
                            $("#errormsg7").html("Wrong Password");
                            user_mobileajax2 = "";
                        }
                        else if (msg == "CorrectPw")
                        {
                            $("#errormsg7").html("");
                            user_mobileajax2 = "item6";
                        }
                    }
                });
            }
        }

    /* ----------------- Run Functions */
    $("#user_email2").on('focusout', validate_email_login);
    $("#user_password2").on('focusout', validate_password_login);
    $("#login").on('click', validate_email_login);
    $("#login").on('click', validate_password_login);

    /* ----------------- Stop on Submit */
    $("#login").click(function()
    {
        if (user_email2 == "" || user_password2 == "" || user_emailajax2 == "" || user_mobileajax2 == "")
        {
            $("#errormsg8").html("Please Fill All Fields (Correctly)")
            return false;
        }
        else
        {
            return true;
        }
    });
});

如果没有错误,则表单只需单击一次即可提交,但如果出现错误,则会纠正这些错误(根据验证规则),然后提交按钮需要两次单击才能提交​​.

尝试过以下的事情

重命名$(“#login”).单击(function()到$(“#login”).on(“click”,function()

$( “#登录”)触发( “点击”). – 返回true后返回true

$(“#login”).click(); – 返回true后返回true

< input type =“button”name =“login”id =“login”value =“Submit”> – 将提交更改为按钮

我尝试了这个解决方案(它不起作用,结果是需要相同的两次点击……)

$(document).ready(function()
{
    /* ----------------- Login Validations Global Variables -----------------   */
    var user_email2 = "";
    var user_password2 = "";
    var user_mobileajax2 = "";
    var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
    /* ----------------- Define Validate Password */
    var validate_password_login = function()
    {
        // Set up the deferred object
        var def = $.Deferred();
        var item5 = $("#user_email2").val();
        var item5 = item5.toLowerCase();
        var item6 = $("#user_password2").val();
        if (item6.length < 8 || item6.length > 20)
        {
            $("#errormsg7").html("Password : 8-20 Characters");
            user_password2 = "";
            // Not a valid password so reject the deferred
            def.reject();
        }
        else
        {
            $("#errormsg7").html("");
            user_password2 = item6;
            $.ajax(
                {
                    method: "POST",
                    url: "classes/validatelogin.PHP?f=2",
                    data: "user_email2=" + item5 + "&user_password2=" + item6
                })
                .done(function(msg)
                {
                    if (msg == "WrongPw")
                    {
                        $("#errormsg7").html("Wrong Password");
                        user_mobileajax2 = "";
                        // The server said the PW was wrong, so reject this
                        def.reject();
                    }
                    else if (msg == "CorrectPw")
                    {
                        $("#errormsg7").html("");
                        user_mobileajax2 = "item6";
                        // Looks like we are valid so we can resolve this
                        def.resolve();
                    }
                })
                .fail(function()
                {
                    // Something went wrong on the server side, so have to reject
                    def.reject();
                });
        }
        // We return the promise
        return def.promise();
    }
    /* ----------------- Run Functions */
    $("#user_password2").on('focusout', validate_password_login);
    // Move to submit handler
    $('form[name="loginform"]').on('submit', function()
    {
        // Set up the validation methods inside $.when
        $.when(validate_password_login())
            .done(function()
            {
                // Done means success!
                return true;
            })
            .fail(function()
            {
                // And fail is obvIoUsly a fail.
                return false;
            });
    });
});

解决方法:

我没有用完整的登录设置完全复制这个,但是我确实通过将ajax.success更改为ajax.error并使用错误的url来触发错误来进行快速测试,然后在错误内部,我将msg变量设置为表示有效响应的字符串,表单不需要两次提交.

这一点,再加上仔细看看代码,我猜这个问题是由于ajax调用引起的竞争条件.

您的点击处理程序设置如下:

$("#login").on('click', validate_email_login);
$("#login").on('click', validate_password_login);
$("#login").click(function() { ... });

在最后一个处理程序内部,代码检查字符串以查看结果是否有效.但是,当它到达那里时,之前的ajax请求可能尚未完成加载,并且这些字符串可能尚未重置.您可以在该函数中添加一些console.log来查看这些值是什么并确认.

因为这些ajax调用是异步的,所以在检查表单是否有效之前,您必须等待它们完成.您正在寻找的是Promises和Deferreds.

我建议将其重构为以下内容:

>在两种验证方法中设置延迟.
>删除#login单击处理程序并将所有内容移动到表单的提交处理程序中.
>在表单的提交处理程序中,使用$.when调用验证方法.

快速代码示例:

// Move to submit handler
$('form[name="loginform"]').on('submit', function() {
    // Set up the validation methods inside $.when
    $.when(validate_email_login(), validate_password_login())
     .done(function() {
        // Done means success!
        return true;
     })
     .fail(function() {
        // And fail is obvIoUsly a fail.
        return false;
     });
});

除了jQuery文档之外,一眼看上去,这看起来像是另一个很好的示例资源和一切的解释:http://jqfundamentals.com/chapter/ajax-deferreds.我认为最像你所拥有的东西是最底层的.

快速设置其中一种验证方法可能看起来像(未经测试):

var validate_password_login = function() {
    // Set up the deferred object
    var def = $.Deferred();
    var item5 = $("#user_email2").val();
    var item5 = item5.toLowerCase();
    var item6 = $("#user_password2").val();

    if (item6.length < 8 || item6.length > 20) {
      $("#errormsg7").html("Password : 8-20 Characters");
      user_password2 = "";
      // Not a valid password so reject the deferred
      def.reject();
    } else {
      $("#errormsg7").html("");
      user_password2 = item6;
      $.ajax({
        method: "POST",
        url: "http://www.google.com",
        data: "user_email2=" + item5 + "&user_password2=" + item6
      })
      .done(function(msg) {
          if (msg == "WrongPw") {
            $("#errormsg7").html("Wrong Password");
            user_mobileajax2 = "";
            // The server said the PW was wrong, so reject this
            def.reject();
          } else if (msg == "CorrectPw") {
            $("#errormsg7").html("");
            user_mobileajax2 = "item6";
            // Looks like we are valid so we can resolve this
            def.resolve();
          }
       })
       .fail(function() {
          // Something went wrong on the server side, so have to reject
          def.reject();
        });
    }

    // We return the promise
    return def.promise();
}

javascript – jquery计数器 – 允许多次点击li但只计算一次

javascript – jquery计数器 – 允许多次点击li但只计算一次

我正在制作一个像隐藏物品一样的迷你游戏.我是jQuery的新手.
我有一个表示页面上图像的项目列表.当需要提示来查找项目时,可以单击列表项目,它将启动动画以显示同名对象的位置.有一个计数器提供3个提示.这一切都有效.

我遇到的问题是,如果您多次单击同一个列表项,则会使用三个提示.如何让计数器只对每个列表项计数一次?因此,换句话说,您可以多次单击列表中的相同项目,但它只会将计数器减一.然后,如果您单击一个不同的列表项,它将再次减少一个计数器.

这是jsfiddle:http://jsfiddle.net/gudinne/ej4mLoze/

谢谢你的指导!

JS

// hintCounter of 3 counts down to 0 and changes behaviors
var hintCounter = 3;

$('.itemList li').on('click', function () {
   // check if has hints
   if (hintCounter > 0) {
       hintCounter--;

$('.xHints').html(hintCounter + ' Hints');
   } else {
       // else show the message out of hints
       $('.directions').html('Sorry you are all<br /> out of hints. <br />Keep Searching!');
   }
});

HTML

<div>
<ul>
    <li>Baseball</li>
    <li>Bacon</li>
</ul>
<div id="hintBox"> <span>You Have</span>
 <span>3 Hints</span>

    <p>Use a hint by clicking on a name in the list.</p>
</div>

CSS

 .itemWrapper {
   border: 2px solid;
   width: 400px;
   height: 271px;
   white-space: normal;
   position: relative;
 }
 .itemList {
   margin: 0;
   padding: 45px 55px;
 }
 .itemList li {
   list-style-type: none;
   position: relative;
   cursor: pointer;
   text-transform: uppercase;
   font-size: 20px;
   text-align: center;
 }
 #hintBox {
   width: 300px;
   margin: 0 auto;
   text-align:center;
   color: blue;
 }
 .xHints {
   font-weight: bold;
 }

解决方法:

您可以简单地添加一个类来告诉它们何时被使用(这也意味着您可以相应地设置它们的样式):

http://jsfiddle.net/TrueBlueAussie/ej4mLoze/1/

$('.itemList').on('click', 'li:not(.used)', function () {
    $(this).addClass("used");

我将事件处理程序更改为委托事件处理程序,以便选择(即不是(.used))将在事件时发生(而不是在事件被注册时).

根据评论更新:

如果你想保留提示,但不减少计数器,你可以在决定减少时简单地测试一个类的存在:

例如http://jsfiddle.net/TrueBlueAussie/ej4mLoze/3/

$('.itemList').on('click', 'li', function () {

    // check if has hints
    if (hintCounter > 0) {
        if (!$(this).hasClass("used")) {
            hintCounter--;
        }

        $('.xHints').html(hintCounter + ' Hints');
    } else {
        // else show the message out of hints
        $('.directions').html('Sorry you are all<br /> out of hints. <br />Keep Searching!');
    }
    $(this).addClass("used");
});

javascript – 一次点击多次触发jQuery点击事件

javascript – 一次点击多次触发jQuery点击事件

当单击一个元素时,我在jQuery中注册多次点击时遇到问题.我已经阅读了Stack Overflow上的一些其他线程来尝试解决它,但我认为这是我编写的代码. HTML代码无效,但这是由某些HTML 5和使用YouTube嵌入代码引起的.没有任何影响点击的内容.

jQuery,在document.ready上触发

function setupHorzNav(portalWidth) {
    $('.next, .prev').each(function() {
        $(this).click(function(e) {
            var target = $(this).attr('href');
            initiateScroll(target);
            console.log("click!");
            e.stopPropagation();
            e.preventDefault();
            return false;
        });
    });

    function initiateScroll(target) {
        var position = $(target).offset();
        $('html, body').animate({
            scrollLeft: position.left
        }, 500);
    }
}

示例HTML

<nav>
    <a href="#countdown-wrapper">Prev</a>
    <a href="#signup-wrapper">Next</a>
</nav>

在Firefox中,单击一下即可记录“Click!” 16次! Chrome只能看到一个,但两个浏览器都显示上述代码存在问题.

我是否错误地编写了代码或者是否存在错误?

– 一些额外的信息——————————————

setupHorzNav由我的代码中的另一个函数调用.我测试了这个,并确认它只在初始加载时调用一次.

if ( portalWidth >= 1248 ) {
    wrapperWidth = newWidth * 4;
    setupHorzNav(newWidth);
}
else
{
    wrapperWidth = '100%';
}

导航’prev-next’有多个实例.所有目标都不同.所有都在同一个html页面内.

<nav>
    <a href="#video-wrapper">Prev</a>
</nav>

解决方法:

您不需要.each()来绑定事件处理程序.试试这个:

$('.next, .prev').click(function(e){
        var target = $(this).attr('href');
        initiateScroll(target);
        console.log("click!");
        e.stopPropagation();
        e.preventDefault();
        return false;
});

编辑:
我认为这是你在setupHorzNav函数中附加事件处理程序的方式.更改它只是附加一次,比如说,$(document).ready()或其他东西.

我已经设法通过从事件处理程序调用的函数附加事件处理程序来获取多个事件处理程序的情况.结果是点击事件处理程序的数量随着每次单击而几何增加.

这是代码:(和jsfiddle演示)

function setupNav() {
    $('.next, .prev').each(function () {
        $(this).click(function (e) {
            setupNav();
            var target = $(this).attr('href');
            console.log("click!");
            e.stopPropagation();
            e.preventDefault();
            return false;
        });
    });
}

setupNav();

了解如何从click事件处理程序调用setupNav()函数,在连续单击时添加多个事件处理程序(以及单击日志消息)

今天关于javascript – 在JQuery中防止多次点击jquery防止重复点击的分享就到这里,希望大家有所收获,若想了解更多关于javascript - 在jQuery中遍历二维数组、javascript – Jquery Ajax表单需要2次点击提交、javascript – jquery计数器 – 允许多次点击li但只计算一次、javascript – 一次点击多次触发jQuery点击事件等相关知识,可以在本站进行查询。

本文标签: