1

我有两个功能。第一个是检查所有输入元素以确保它们被正确填充的那个。每件事都运行良好,但随着第二个函数开始起作用(第二个函数 'newInput()' 添加输入),第一个函数不能再应用了。

调试器说 atpositionSec = emailSec.indexOf("@") 中的 emailSec 未定义。

有没有人知道解决方案?

标记在这里:

<--!The HTML-->
<form method="post" action="" id="cms" name="cms" onSubmit="return error()">
<table>
     <tbody id="myInput">
          <tr>
              <td>
                  <label>Role:<span> *</span></label>
                  <input type="text" name="role" id="role" value="" class="required span3" role="input" aria-required="true" />
              </td>
              <td>
                  <label>Email:<span> *</span></label>
                  <input type="email" name="emailSec" id="emailSec" value="" class="required span3" role="input" aria-required="true" />
              </td>
              <td>
                 <button style="height: 20px;" title='Add' onclick='newInput()'></button>
              </td>     
          </tr> 
     </tbody>
     <input type="hidden" name="count" id="count" vale=""/>
</table>
    <input type="submit" value="Save Changes" name="submit" id="submitButton" title="Click here!" />
</form>

第一个功能:

function error()
{
var emailSec = document.forms['cms']['emailSec'].value,
    role = document.forms['cms']['role'].value,
    atpositionSec = emailSec.indexOf("@"),
        dotpositionSec = emailSec.lastIndexOf(".");                     


        if( topicSec == '' || topicSec == null)
        {
            alert ("Write your Topic!");
            return false;
        }
        else if(role == '' || role == null)
        {
            alert ("Enter the Role of the email owner!");
            return false;
        }
        else if(emailSec == '' || emailSec == null || atpositionSec < 1 || dotpositionSec < atpositionSec+2 || dotpositionSec+2 >= emailSec.length)
        {
            alert ("Enter a valid Email!");
            return false;
        }
               else return true;                    



}

第二个功能:

//The Javascript - Adding Inputs 
var i = 1,
count;


function newInput()
{
document.getElementById("myInput").insertAdjacentHTML( 'beforeEnd', "<tr><td><input   type='text' name='role" + i + "' id='role' value='' class='required span3' role='input' aria-required='true' /></td><td><input type='email' name='emailSec" + i + "' id='emailSec' value='' class='required span3' role='input' aria-required='true' /></td><td><button style='height: 20px;' title='Remove' onclick='del(this)'></button></td></tr>");


count = i;
document.forms["cms"]["count"].value = count; 
i++;
}

// Removing Inputs
function del(field) 
{
--count;
--i;
document.forms["cms"]["count"].value = count; 
field.parentNode.parentNode.outerHTML = "";
}
4

1 回答 1

2

问题是,在第一次添加之后,它document.forms['cms']['emailSec']变成了一个包含所有元素的数组emailSec,因此您需要使用document.forms['cms']['emailSec'][i].

为了省点麻烦,您可以使用html5 中输入元素的模式属性来自动执行此操作。此外,您可以使用<input type="email" required />我认为几乎可以为您完成所有工作的东西。

于 2012-08-28T11:39:14.903 回答