简体   繁体   中英

How to shorten my function in javascript?

Well, I know this is probably my another stupid question but I'm tired of looking for the answer and I'm not clever enough to figure it out myself.

My script looks like this and I wonder how can I make it shorter as there will be many more exercises like this. As you can see every function does the same thing. Possible answers are only three: 'is', 'are' and 'am'.

Anyone help please?

<p>1. He <input type="text" id="ex1.1" size="4"> funny. <input type="button" value="Check!" onclick="a()"> <span id="err1"></span></p>

<script>
function a() {
   var a=document.getElementById("ex1.1");
   if((a.value=="is")) {
      document.getElementById('err1').innerHTML= 'Correct!';
      document.getElementById('err1').style.color = "green";
   } else {
      document.getElementById('err1').innerHTML= 'Wrong :( Try again!';
      document.getElementById('err1').style.color = "red";
   }

}
</script>

<p>2. I <input type="text" id="ex1.2" size="4"> cool. <input type="button" value="Check!" onclick="b()"> <span id="err2"></span></p>
<script>

function b()
{
   var a=document.getElementById("ex1.2");
   if((a.value=="am")) {
      document.getElementById('err2').innerHTML= 'Correct!';
      document.getElementById('err2').style.color = "green";
   } else {
      document.getElementById('err2').innerHTML= 'Wrong :( Try again!';
      document.getElementById('err2').style.color = "red";
   }

}
</script>

<p>3. She <input type="text" id="ex1.3" size="4"> pretty. <input type="button" value="Check!" onclick="c()"> <span id="err3"></span></p>
<script>

function c() {
   var a=document.getElementById("ex1.3");
   if((a.value=="is")) {
      document.getElementById('err3').innerHTML= 'Correct!';
      document.getElementById('err3').style.color = "green";
   } else {
      document.getElementById('err3').innerHTML= 'Wrong :( Try again!';
      document.getElementById('err3').style.color = "red";
   }
}
</script>

<p>4. We <input type="text" id="ex1.4" size="4"> fast. <input type="button" value="Check!" onclick="d()"> <span id="err4"></span></p>
<script>

function d()
{
   var a=document.getElementById("ex1.4");
   if((a.value=="are")) {
      document.getElementById('err4').innerHTML= 'Correct!';
      document.getElementById('err4').style.color = "green";
   }  else {
      document.getElementById('err4').innerHTML= 'Wrong :( Try again!';
      document.getElementById('err4').style.color = "red";
   }
}
</script>

There are only three things that change in each function - the element IDs and the desired answer - these should therefore be parameters.

You should also apply the Don't Repeat Yourself (DRY) Principle within the function itself and avoid repeated unnecessary calls to document.getElementById

function checkAnswer(inputId, outputID, rightAnswer) {
    var input = document.getElementById(inputId);
    var output = document.getElementById(outputId);
    var correct = (input.value === answer);

    // remainder left as an exercise for the OP, except to
    // note that the code would be potentially shortened
    // even further with use of the ternary ?: operator
    // instead of an if/else branch
    ...
}

Example usage:

checkAnswer('ex1.2', 'err2', 'am')

Extracting common elements from a piece of code (and if necessary parameterising that code) is known as "refactoring".

You should note that element IDs with decimal points in are only permitted in HTML5. You would be better using an underscore.

You are using uncecessarily long calls to get objects, such as:

document.getElementById('err1');

You can shorten your code a lot by doing what you are doing with your a variable. Such as:

var err3 = document.getElementById('err3');

After that you can do:

if(a.value == "is") {
    err3.innerHTML= 'Correct!';
    err3.style.color = "green";
} else{
    err3.innerHTML= 'Wrong :( Try again!';
    err3.style.color = "red";
}

Also, notice that you have a function called a , and inside it a variable called a . Careful with that... It can be useful in some situations but given the kind of help you are asking for here, you probably should avoid giving a function and a variable inside it the same name.

 function displayMessage(inputId, messageId, valueToCheck) {
        var inputEle = document.getElementById(inputId),
            messageEle = document.getElementById(messageId);
        if (inputEle && messageEle) {
            if (inputEle.value == valueToCheck) {
                messageEle.innerHTML = 'Correct!';
                messageEle.style.color = "green";
            }
            else {
                messageEle.innerHTML = 'Wrong :( Try again!';
                messageEle.style.color = "red";
            }
        }
    }

Check this jsfiddle

http://jsfiddle.net/7v7y5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM