我正在尝试使用jQuery click方法设置表单。对于html我不想使用onClick,而是从id clickMe调用以显示名称。它似乎没有工作。这可能吗?如果是的话,我错过了什么?
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>
答案 0 :(得分: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!
答案 1 :(得分: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());
});
});