简单的问题。这怎么不行?它是一个温度转换器,带有F2C和C2F的部件。我是编程的新手。
HTML:
Convert Celsius to Fahrenheit:
Enter Celsius Value:
<input id="valToConvertToF" type="text" size="7">
Farenheit Value:
<input id="result1" type="text" size="7" readonly />
<button id="fButton" type="button">Convert!</button>
Convert Fahrenheit to Celsius:
Enter Farenheit Value:
<input id="valToConvertToC" type="text" size="7">
Celsius Value:
<input id="result2" type="text" size="7" readonly />
<button id="cButton" type="button">Convert!</button>
jQuery:
$(function(){
/*celsius to f*/
var inputVal1 = $("#valToConvertToF");
var outputVal1 = $("#result1");
var commandButton1 = $("#fButton");
function efIt()
{
// read value entered by user
// convert it from string to number
var initialVal1 = parseFloat(inputVal1.value);
// bulletproof
if(isNaN(initialVal1))
{
window.alert("Enter a valid number! \nTry again!");
inputVal1.value = "";
outputVal1.value = "";
}
else
{
// calculate it, to 2 decimal points
var calculatedVal1 = ( (9/5) *initialVal1 + 32 ).toFixed(2);
// display square
outputVal1.text(calculatedVal1);
}
}
// when referring to function, NO PARENS
commandButton1.click(efIt);
/*next*/
/*farenheit to c*/
var inputVal2 = $("#valToConvertToC");
var outputVal2 = $("#result2");
var commandButton2 = $("#cButton");
function cIt()
{
// read value entered by user
// convert it from string to number
var initialVal2 = parseFloat(inputVal2.value);
// bulletproof
if(isNaN(initialVal2))
{
window.alert("Enter a valid number! \nTry again!");
inputVal2.value = "";
outputVal2.value = "";
}
else
{
// calculate it, to 2 decimal points
var calculatedVal2 = ( (5/9) *(initialVal2 - 32)).toFixed(2);
// display square
outputVal2.text(calculatedVal2);
}
}
// when referring to function, NO PARENS
commandButton2.click(cIt);
});
答案 0 :(得分:3)
jQuery对象没有value
属性,请使用val
方法:
var initialVal1 = parseFloat(inputVal1.val());
和
inputVal1.val("");
outputVal1.val("");
和
var initialVal2 = parseFloat(inputVal2.val());
和
inputVal2.val("");
outputVal2.val("");
请勿使用text
方法设置输入值,请使用val
方法:
outputVal1.val(calculatedVal1);
和
outputVal2.val(calculatedVal2);
答案 1 :(得分:0)
试试这个:
/*celsius to f*/
$("#fButton").click(function()
{
var inputVal1 = $("#valToConvertToF");
var outputVal1 = $("#result1");
// read value entered by user
// convert it from string to number
var initialVal1 = parseFloat(inputVal1.val());
// bulletproof
if(isNaN(initialVal1))
{
window.alert("Enter a valid number! \nTry again!");
inputVal1.val("");
outputVal1.val("");
}
else
{
// calculate it, to 2 decimal points
var calculatedVal1 = ( (9/5) *initialVal1 + 32 ).toFixed(2);
// display square
outputVal1.val(calculatedVal1);
}
}
);