首页 > 解决方案 > 为什么只有某些 javascript 函数在 HTML 脚本标签中起作用?

问题描述

我想我可能已经错误地格式化了我的一些 javascript 函数——我是 html 的新手。其中只有一个有效。它们都是脚本标签,但包含完整的程序。这是代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>State Tax Calculator</title>

  <body>
    <form name="stateSelect">
      <!sets value to options, tax rate to state>
      Select which state you are purchasing from:
            <select id="stateOptions" onchange="showData()">
            <option value='.04'>Alabama</option>
            <option value='0'>Alaska</option>
            <option value='.0560'>Arizona</option>
          </select>
        </form>
        <p id="firstP">&nbsp;</p>
    <script>

    function showData() {
        //extracts value from option selected
        var theSelect = stateSelect.stateOptions;
        var firstP = document.getElementById('firstP');
        firstP.innerHTML = ('Your state retail tax rate is: ' +
                          theSelect[theSelect.selectedIndex].value * 100 + '%');
    }

    function askPrice() {
      //asks the user for the price of their item
      var price = Window.prompt("What's the price of your retail item?","0");
          if (person == null || person == "") {
            txt = "User cancelled the prompt.";
          }
      var num1 = parseInt(price);
    }

    function finalCost(){
      //multiplies the original price with the state tax rate to get final cost
      return askPrice * theSelect[theSelect.selectedIndex].value;
    }

    </script>
  </body>
</html>

只有函数 showData 有效——我的其他函数格式是否错误?它们应该在单独的脚本标签中吗?提前致谢!

标签: javascripthtml

解决方案


你没有运行 askPrice 和 finalCost 函数?这些功能需要根据特定功能起作用,但您尚未在页面中定义它们。

我认为这就是你想要做的。我将所有功能放在一个功能下。

现在,当您在选择框上进行更改时,它会从用户那里接收价格信息,并根据屏幕上的价格信息显示更改。

既然你还没有明确说明你想要什么,那我就只能这样了。如果你理解你的逻辑,你就会做出必要的安排。

let firstP = document.getElementById('firstP');
function showData() {
    let theSelect = stateSelect.stateOptions;
    let selectValue = theSelect[theSelect.selectedIndex].value;
    let getUserPrice = window.prompt("What's the price of your retail item?","0");
    firstP.innerHTML = 'Your state retail tax rate is:' + (getUserPrice * parseFloat(selectValue)) + "%"

}

推荐阅读