2014-02-14 42 views
1

我创建了一个真正简单的表单,并使用JS访问单选按钮的值,然后快速计算并在基于函数的弹出框中返回一个字符串。问题是当按钮被点击时,弹出窗口返回被调用函数的代码而不是字符串。JavaScript确认框返回代码而不是函数值

 <div id="questionaire"> 
     <div id="question1">  
      <h2>How familiar are you with Javascript?</h2><br> 
      <form id="first_q"> 
       <input type="radio" name="q1" value="4">Very Experienced.</input><br> 
       <input type="radio" name="q1" value="3">I've Worked with the Basics.</input><br> 
       <input type="radio" name="q1" value="2">I Only Know Its a Programming Language.</input><br> 
       <input type="radio" name="q1" value="1">Java...Mmm, Coffee sounds GOOD!</input> 
      </form> 
     </div> 
     <div id="question2"> 
      <h2>How much do you like to code?</h2><br> 
      <form id="second_q"> 
       <input type="radio" name="q2" value="4">I think about coding during sex!</input><br> 
       <input type="radio" name="q2" value="3">It's safe to say, I take coding pretty_seriously.</input><br> 
       <input type="radio" name="q2" value="2">I would consider it my cold-weather hobby.</input><br> 
       <input type="radio" name="q2" value="1">Technology is cool.</input> 
      </form> 
     </div> 
    </div> 
    <div id="answer"> 
     <button id="color-switcher">TELL ME MORE...</button> 
    </div> 

外部链接的JS

var q1_rating = function() { 
var first_q_answer = document.getElementsByName("q1"); 

for(var i = 0; i < first_q_answer.length; i++) { 
    if(first_q_answer[i].checked == true) { 
    q1_value = first_q_answer[i].value; 
    } 
} 

return parseFloat(q1_value); 
}; 

var q2_rating = function() { 
var second_q_answer = document.getElementsByName("q2"); 

for(var i = 0; i < second_q_answer.length; i++) { 
    if(second_q_answer[i].checked == true) { 
    q2_value = second_q_answer[i].value; 
    } 
} 

return parseFloat(q2_value); 
}; 

var final_rating = function() { 
total_value = (q1_rating + q2_rating); 

if (total_value > 6) { 
    return "You're a TRUE NERD ready to conquer the world."; 
} else if (total_value > 4 && total_value <=6) { 
    return "You need some more work, but you're coming along nicely."; 
} else if (total_value >2 && total_value <=4) { 
    return "You need to step up your nerd game pronto!"; 
} else { 
    return "You're more jock than nerd"; 
} 
}; 

document.getElementById('color-switcher').addEventListener('click', function(){ 
    confirm(final_rating); 
}) 

回答

3

你需要调用final_rating功能

confirm(final_rating()); 

目前,你传递函数的引用

+0

哦,伙计!绝对需要打电话给我的功能。谢谢你的新鲜眼睛。 – Jay