好的,我会分解它。
首先,此解决方案使用 jQuery 库,因此您需要在 <HEAD> 部分中引用它。您将非常希望引用将放置代码的 javascript 文件:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- You need to define the file name and path as appropriate for yourself. -->
<script type="text/javascript" src="http://path-to-your-url.com/scripts/script.js"></script>
</head>
...
</html>
接下来,您需要对标记进行一些小的更改。
<input value="42500" type="text" name="pharmacist" />
<select>
<input value="17500" type="text" name="dispenser" />
变成:
<input value="42500" type="text" name="pharmacist" id="pharmacist" />
<select id="rate">
<input value="17500" type="text" name="dispenser" id="dispenser" />
关键变化是新的id 属性。您的 javascript 将使用这些来识别代码中的关键元素(您可以为此使用 name 属性,正如 JQone 建议的那样 - 从样式的角度来看,我更喜欢使用 id并且因为 jQuery/CSS 选择器代码更小)。
最后,您创建一个 javascript 文件(我在这里称其为“script.js”)并将其放置在网站的正确文件夹中(与 HTML 文档的 HEAD 部分中使用的路径保持一致,此将是网站根文件夹的子文件夹,称为“脚本”)。该文件将包含以下内容:
// This code sets up the javascript. It is saying: 'when the document is ready, register the "changeRate" function with the "change" event of the select box'. So whenever the select box's value is changed, the function will be called.
$( document ).ready( function() {
$( 'select#rate' ).change( changeRate );
} );
// This sets the values of the text values based upon the selected rate and the existing value.
var changeRate = function() {
var rate = $( this );
var pharmacist = $( 'input#pharmacist' );
var dispenser = $( 'input#dispenser' );
if ( rate.val() == 'perhour' ) {
pharmacist.val( calculateHourlyFromAnnual( pharmacist.val() ) );
dispenser.val( calculateHourlyFromAnnual( dispenser.val() ) );
}
else if ( rate.val() == 'perannum' ) {
pharmacist.val( calculateAnnualFromHourly( pharmacist.val() ) );
dispenser.val( calculateAnnualFromHourly( dispenser.val() ) );
}
};
// Calculates an hourly rate based upon the supplied per annum rate. At the moment this doesn't take into account scenarios where the provided value is empty or is not a number so you will need to adjust appropriately.
function calculateHourlyFromAnnual( annumRate )
{
-- Making the assumption that a per-annum rate of $50,000 translates to an hourly rate of $50
return annumRate / 1000;
}
// Calculates a per-annum rate based upon the supplied hourly rate. At the moment this doesn't take into account scenarios where the provided value is empty or is not a number so you will need to adjust appropriately.
function calculateAnnualFromHourly( hourlyRate )
{
-- Making the assumption that an hourly rate of $50 translates to a per-annum rate of $50,000
return hourlyRate * 1000;
}
很可能,我用于计算利率变化的公式过于简单,但我不知道您的情况下的业务需求。您必须自己找出正确的公式。
基本上,如果您按照这些步骤操作,当您在每年和每小时之间切换选择列表时,应该更改这些值。