2

I am trying to setup a form using jQuery click method. For html I don't want to use onClick but rather call from the id clickMe to display name. It doesn't seem to be working. Is this possible? if so, What am I missing?

var getName = function ()
{
if (document.getElementById("FirstName").value == "" || document.getElementById("LastName").value == "")
{
return ("Please enter your first name and last name.");
}

else {var fullName = document.getElementById("FirstName").value + ' ' + document.getElementById("LastName").value;
return fullName;
}
}

var displayName = function () 
{

    $(document).ready(function(){   
    $("#clickMe").click(function(){
        alert(displayName());
    }); 
}); //end ready

}

HTML

<form name="form" id="form" method="post" action="">  

 <p class="FirstName">  
    <label for="FirstName">First Name:</label>
  </p>
    <p>
    <input name="FirstName" type="text" id="FirstName" />  

</p>  

<p class="LastName">  
    <label for="LastName">Last Name:</label></p>
    <p>
    <input name="LastName" type="text" id="LastName" />  

   </p>


<p class="submit">  
    <input name="submitButton" type="button" id="clickMe" value="Display Name" />
  </p>  
 </form> 
4

2 回答 2

2

你看,这段代码:

$(document).ready(function(){   
   $("#clickMe").click(function(){
      alert(displayName());
   }); 
});

在里面displayName

var displayName = function () 
{
...
}

并且displayName永远不会被调用。因此,该click()事件永远不会设置。

要么将该$(document).ready()代码带到外面,要么调用displayName,如下所示:

var getName = function ()
{
    if (document.getElementById("FirstName").value == "" || document.getElementById("LastName").value == "")
    {
        return ("Please enter your first name and last name.");
    }
    else {
        var fullName = document.getElementById("FirstName").value + ' ' + document.getElementById("LastName").value;
        return fullName;
    }
}

var displayName = function () 
{
    $(document).ready(function(){   
        $("#clickMe").click(function(){
            alert(displayName());
        }); 
    }); //end ready

}

$(function() { displayName(); }); // <-- calling displayName here!
于 2013-04-21T22:38:54.767 回答
1

请参阅 acdcjunior 的答案,以正确分析现有代码的问题。事实上,我认为您的displayName功能在这里是多余的,您可以通过如下更新代码来大大简化事情:

$(document).ready(function() {

    var getName = function () {
        if (document.getElementById("FirstName").value == "" || document.getElementById("LastName").value == "") {
            return ("Please enter your first name and last name.");
        } else {
            var fullName = document.getElementById("FirstName").value + ' ' + document.getElementById("LastName").value;
            return fullName;
        }
    }

    $("#clickMe").click(function(){
        alert(getName());
    }); 
});
于 2013-04-21T22:33:00.723 回答