需要单击按钮两次以触发功能

2 javascript onclick

我知道这很难理解,但请试一试.看一下截图.

小输入框的名称是murl.

add()用于提交表单.如果murl为空,则表单必须直接提交,如果表单不为空,murl则必须根据数据库检查该表项是否存在.如果它不存在add()则调用.

问题是button必须单击两次才能触发该功能.

按钮上的代码是:

<button type="button" value="My button value" onclick="javascript: niju();" name="microsubmit" id="microsubmit">button</button> 
Run Code Online (Sandbox Code Playgroud)

该按钮调用的JavaScript是:

function niju()
{
    var flag=1;
    var micro=document.getElementById('murl').value;

    $('#microsubmit').click(function()
    {

        if(micro=="")
        {
            add();
        }
        else
        {
            //remove all the class add the messagebox classes and start fading
            $("#msgbox")
                .removeClass()
                .addClass('messagebox')
                .text('Checking...')
                .fadeIn("slow");

            //check the username exists or not from ajax
            $.post("<?php echo SITE_ROOT;?>inc/user_availability.php",
                { murl: $("input:murl").val()  },
                function(data)
                {
                    if(data=='no') //if username not avaiable
                    {
                        $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
                        {
                            //add message and change the class of the box and start fading
                            $(this)
                                .html('This User name Already exists')
                                .addClass('messageboxerror')
                                .fadeTo(900,1);

                            flag=0;
                        });
                    }
                    else
                    {
                        $("#msgbox")
                            //start fading the messagebox
                            .fadeTo(200,0.1,function()
                            {
                                //add message and change the class of the box and start fading
                                $(this)
                                    .html('Username available to register')
                                    .addClass('messageboxok')
                                    .fadeTo(900,1);   

                                flag=1;
                                add();
                            });
                    }
                });
        }
    });

    if(micro=="" && flag==1)
    {
        add();
    }
}
Run Code Online (Sandbox Code Playgroud)

截图:

截图

Pao*_*ino 6

它被点击两次,因为你定义#microsubmitclick函数内部事件.因此,第一次单击绑定事件处理程序时,第二次事件处理程序就位并被触发.我没有完成你想要完成的逻辑,但我的猜测是,如果你将事件绑定器移到函数之外并确保所有变量都在正确的范围内,那么它将起作用.