简体   繁体   English

如何通过 Id 获取数组元素进行比较?

[英]How to can I get array elements by Id to do Comparisons?

My find matches function does not seem to be working.我的查找匹配功能似乎不起作用。

I want to get an array ( [] ) element by id and do comparisons with it.我想通过 id 获取一个数组 ( [] ) 元素并与它进行比较。

The function is supposed to go into the array and generate a random person, then display the match in the text area "showmatches".该函数应该进入数组并生成一个随机人,然后在文本区域“showmatches”中显示匹配项。

I am not sure if the random person is being generated nor if the criteria are being matched in the comparison.我不确定是否正在生成随机人,也不确定在比较中是否匹配标准。

<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>

Do these steps.做这些步骤。 First you have two window.onload = () (As you are not using addEventListener only one event will be attached).首先你有两个 window.onload = () (因为你没有使用 addEventListener 只会附加一个事件)。

Steps:脚步:

  1. Keep everything intact, just remove the window.onload from both places.保持一切完好,只需从两个地方删除 window.onload 即可。 Keep all code inside load intact.保持负载内的所有代码完好无损。
  2. Move the entire code block just to the bottom of the html above closing tag.将整个代码块移动到结束标记上方的 html 底部。 (Doing so, will make window.onload redundant.) (这样做会使 window.onload 变得多余。)

Put console.log() in the click handler and see if it's working (it will)将 console.log() 放在点击处理程序中,看看它是否工作(它会)

Let us know.让我们知道。

NOTE: On other hand there are better way to code this, for eg wait for DOMContentLoaded for attaching event etc., but it's too big to discuss here.注意:另一方面,有更好的编码方式,例如等待 DOMContentLoaded 以附加事件等,但在这里讨论太大了。 First make this work, then we can recommend better approaches.首先使这项工作,然后我们可以推荐更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取所有LI UL元素ID值并将它们放置在JavaScript数组中? - How do I get all the LI UL elements ID value and place them in a JavaScript array? 如何从元素集中获取id并保存在数组中? - how can get id from set of elements and save in array? 如何让 jQuery 选择带有 . (句号)在他们的身份证上? - How do I get jQuery to select elements with a . (period) in their ID? 如何在鼠标悬停时获取元素ID并将其分配给变量? - How can I get an elements ID on mouseover and assign it to a variable? 如何从元素数组中动态获取元素的值? - How do I dynamically get the value of an element from an array of elements? 如何从 Javascript 中的数组中获取元素的随机组合? - How do i get a random combination of elements from an array in Javascript? 如何获取没有括号且没有换行符的数组元素? - How can I get the elements of an array without the brackets and no line break? 如何从firebase中json内部的数组中获取元素? - How can i get the elements from an array inside of json in firebase? 如何获取数组中图像的 src 和 ID - How can I get the src and ID of an image in an array 如何通过 id 将获取元素的值分配到 Javascript 中的数组中? - How can I assign value of get element by id into array in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM