首页 > 解决方案 > 如何通过 Id 获取数组元素进行比较?

问题描述

我的查找匹配功能似乎不起作用。

我想[]通过 id 获取一个数组 ( ) 元素并与之进行比较。

该函数应该进入数组并随机生成一个人,然后在文本区域“showmatches”中显示匹配。

我不确定是否正在生成随机人,也不确定在比较中是否匹配标准。

<html>
    <head> 
        <script>

var records = [];

function calculateAge() 
{ 
    var dob = document.getElementById('dob').value; 
    var dobInput = new Date(dob);
    
    var now     = new Date(); 
    var year    = now.getFullYear(); 
    var month   = now.getMonth(); 
    var day     = now.getDate(); 
    
    var birthyear   = dobInput.getFullYear(); 
    var birthmonth  = dobInput.getMonth(); 
    var birthday    = dobInput.getDate(); 
    
    var bYear   = year - birthyear; 
    var bMonth  = month - birthmonth; 
    var bDay    = day - birthday; 
    
    if (bYear < 18 || bYear > 75)
    {  
        alert("Age cannot be less than 18 or greater than 75"); 
        return false; 
    }else{
        document.getElementById("age").value = bYear + "years old";
    }
    //document.getElementById("age").value = bYear + "years old";
} 
        
function showAll() 
{ 
    show = document.getElementById("showallpersons").innerHTML=records;
    show.value = records.join("\n");
    
} 
(window.onload = () => {
    var findmatches=document.getElementById('findmatches');
    if(findmatches){
        findmatches.addEventListener('click', findMatches, false);
    }
    function findMatches(e)
    {
        e.preventDefault();
        for(var counter=0; counter<records.length; counter++)
        {
            var currposn = records[counter].value;
            var show = document.getElementById("showallmatches").innerHTML= currposn.fname + currposn.lname;
            show.value = currposn.join("\n");
            
            do
            {
                //From here 
                var randpson = Math.random() * records.length;
                randpson = Math.floor(randpson); //To here works, I know that for sure
                
                
                //I'm not sure if the conditions for the if statements are correct
                if(((randpson.age - currposn.age) <= 10) || ((randpson.age - currposn.age) >= 20))
                {
                    if(((randpson.height - currposn.height) <= 10) || ((randpson.height - currposn.height) >= 20))
                    {
                        var display = document.getElementById("showmatches").innerHTML= "Matched to: " +randpson.fname + randpson.lname;
                        //display.value = "Matched to: " + randpson.fname + randpson.lname;
                        break;
                    }
                }
            } while(counter < 10){
                
                //var newDisplay = document.getElementById("showallmatches").innerHTML= null;
            }   
            //console.log(findMatches());
        }
        
    }
})()
(window.onload = () => {
    var submit = document.getElementById('submit');
    if(submit){
        submit.addEventListener('click', addnew, false);
    }
    function addnew(event)
    {
        //Prevents default submit event
        event.preventDefault();
        //Accept values entered in form
        var fname = document.getElementById('fname').value;
        var mname = document.getElementById('mname').value;
        var lname= document.getElementById('lname').value;
        var dob= document.getElementById('dob').value;
        var gender = document.forms['Information']['gender'].value;
        var age = document.getElementById('age').value;
        parseInt(age);
        var bodyType = document.getElementById('Body Type').value;
        var occu= document.getElementById('occu').value;
        var height= document.getElementById('height').value;
        
        if (fname==null || fname=="")
        {  
            alert("A first name is required");  
            return false;
        }
        if(mname==null || mname=="")
        {  
            alert("A middle initial is required");  
            return false;
        }
        if (lname==null || lname=="")
        {  
            alert("A last name is required");  
            return false;
        }
        if(dob==null || dob=="")
        {
            alert("A DOB is required");
            return false;
        }
        if (gender == "") 
        {
            alert("Please select a gender");
            return false;
        } 
        
        if(height <= 170 || height >= 200)
        {
            alert("A height between 170, not less and 200, not more is required");
            return false;
        }
        if(bodyType==null || bodyType==""){
            alert("Please choose a body type");
            return false;
        }
        if(occu==null || occu=="")
        {
            alert("Please enter an occupation");
            return false;
        }
        //Append To array
        
        records.push(fname);
        records.push(mname);
        records.push(lname);
        records.push(gender);
        records.push(age);
        records.push(bodyType);
        records.push(occu);
        records.push(height);
        
        for(i=0;i<records.length;i++)
        {
            console.log(records[i]);
        }
        document.getElementById("Information").reset();
    }
})()
        </script>
    </head> 
    <body>
        <div class="wrapper">
            <header class="page-header">
                <nav>
                    <button class="cta-contact">Contact Us</button>
                </nav>
            </header>
        </div>
        <div class="space">
            <h1>
                <marquee behavior="scroll" direction="right">What are you waiting for? Find your "one" now.</marquee>
            </h1>
        </div>
        <div class="container">
            <form name="Information" id="Information">
                <fieldset> 
                    <legend>Personal Information</legend>
                First Name: 
                <input id="fname" type="text"  size=40 placeholder='First Name' minlength=4 maxlength=40 required />
                <br/><br/>
                Middle Initial: 
                <input id="mname" type="text"  size=3 placeholder='M Intial' maxlength=1 required />
                <br/><br/>
                Last Name:
                <input id="lname" type="text"  size='40' placeholder='Last Name' minlength='4' maxlength='40' required />
                <br/><br/>
                Date of Birth 
                <input id="dob" type="date" onchange="calculateAge()"/>
                <br/><br/>
                Gender: 
                <input id="male" type="radio" value='M' name="gender" required/> Male
                <input id="female" type="radio" value='F' name="gender" required/> Female
                <br/><br/>
                Age: <input type="text" id="age" disabled />
                <br/>
                Body Type:
                <select id="Body Type">
                    <optgroup label="Female" id="FemaleOpt">
                        <option value="Apple"> Apple </option>
                        <option value="Pear"> Pear </option>
                        <option value="Pencil"> Pencil </option>
                        <option value="Hourglass"> Hourglass </option>
                        <option value="Round"> Round </option>
                    </optgroup>
                    <optgroup label="Male" id="MaleOpt">
                        <option value="Oval"> Oval </option>
                        <option value="Triangle"> Triangle </option>
                        <option value="Rectangle"> Rectangle </option>
                        <option value="Rhomboid">Rhomboid </option>
                        <option value="Inverted">Inverted Triangle</option>
                    </optgroup>
                </select>
                <br/><br/>
                Occupation:  
                <input id="occu" type="text" size=30 maxlength=30 required />
                <br/><br/>
                Height(in cm):  
                <input id="height" type="number" size="3" min="171" max="199" value="" required /><br>
                <br/><br/>
                <textarea id="showallpersons" name="Show All Persons" onclick="showAll()" disabled></textarea>
                <textarea id="showmatches" name="Show All Matches" onclick="findMatches()" disabled></textarea>
                <br/><br/>
                <button id="submit" type="submit">Submit</button>
                <button id="findmatches" type="button">Find Matches</button>
            </fieldset>     
        </form>
    </div>
    </body>
</html>

标签: javascripthtmlarrays

解决方案


执行这些步骤。首先你有两个 window.onload = () (因为你没有使用 addEventListener 只会附加一个事件)。

脚步:

  1. 保持一切完好,只需从两个地方删除 window.onload 即可。保持负载内的所有代码完好无损。
  2. 将整个代码块移动到结束标记上方的 html 底部。(这样做会使 window.onload 变得多余。)

将 console.log() 放在点击处理程序中,看看它是否工作(它会)

让我们知道。

注意:另一方面,有更好的编码方法,例如等待 DOMContentLoaded 来附加事件等,但这里讨论太大了。首先完成这项工作,然后我们可以推荐更好的方法。


推荐阅读