0

我想减去 2 个值,并立即使用 javascript 进行计算。我需要找到一种<select>在 JS 中定位第二个 id 的方法,因为我回显了这些选项,所以我这样做:

<tr> <!-- first row, with css -->
<td style="width:50%;">From</td>
<td style="width:50%;">
    <select name="fromlevel" id="fromlevel" style="width:100%; text-align:center; font-weight:bold;">
        <?php 
        $i = 1;
        while ($i < 91) {
            echo '
            <option value=f' . $i . ' name=f' . $i . '>' . $i . '</option>';
            $i++;
        }
        ?>  
    </select>
</td>
</tr>
<tr> <!-- second row, with css -->
<td>To</td>
<td>
    <select name="tolevel" id="tolevel" style="width:100%; text-align:center; font-weight:bold;">
        <?php 
        $i = 1;

        while ($i < 91) {
            echo '
            <option value=t' . $i . ' name=t' . $i . '>' . $i . '</option>';
            $i++;
        }
        ?>  
    </select>
</td>
</tr>

我用 f1、f2、f3、f4 等和 t1、t2、t3、t4 等引用了 ID。我如何在 JS 中区分它们?

如果我只是将第一个的 ID<select>引用为 $i,则下面的 JS 可以工作,我对 JS 非常不利,而且我不知道如何使该引用为 f$i

var level_current_prices = {};

for(var i = 1; i <= 90; i++ ) {
   level_current_prices[i] = i;
}

function getCurrentLevel() { // current level, from
    var levelSetPrice=0;
    var theForm = document.forms["priceCalcForm"];
    var selectedLevel = theForm.elements["fromlevel"];
    levelSetPrice = level_current_prices[selectedLevel.value];
    return levelSetPrice;
}

function calculateTotal() {
    var LevelPrice = getCurrentLevel();
    var divobj = document.getElementById('totalPrice');
    divobj.style.display='block';
    divobj.innerHTML = "Total Price For the Leveling $"+LevelPrice;
}

function hideTotal() {
    var divobj = document.getElementById('totalPrice');
    divobj.style.display='none';
}

document.forms['priceCalcForm'].fromlevel.onchange = function () {
   calculateTotal();
}
4

1 回答 1

0

对你的问题有点困惑。我想你在谈论以下几行?

for(var i = 1; i <= 90; i++ ) {
   level_current_prices[i] = i;
}

用数据预先填充对象,索引level_current_prices是一个字符串,而不是一个数字(那将是一个数组)。您几乎可以在括号内执行您想要的操作来生成密钥,但是您所需要的只是level_current_prices['f'+i]

如果这不是您的意思,请澄清您的问题。

如果这是您想要的,您可以使用 php.ini 预先生成对象(作为 JSON)。

<?php
  $i=1;
  $out = "{";
  while ($i<91) {
    $out .= "\"t".$i."\"=".$i.",";
    $i++;
  }
  $out .="};";
  echo "var level_current_prices = ".$out;
?>

自从我使用 php 以来已经有一段时间了,所以你也许可以做得更好:D。

于 2013-02-23T22:40:58.573 回答