javascript没有在Ruby on Rails上执行onClick

时间:2017-06-29 23:40:33

标签: javascript html ruby-on-rails onclick

尝试使用一些简单的javascript工作,但它没有执行onClick或onChange。

应用程序/视图/选择器/ index.html.erb

<form name="grams_calc">
    <label for="coffee">How much coffee (grams) do you want to make?</label><br/>
    <input type="text" id="coffeeLiquidMake" placeholder="One cup = 300 grams." onChange="finalCoffee()" style="width: 250px">grams.
    <br/>
    <input type="button" value="Give Me Coffee!" onClick="calcBrew(document.getElementById('coffeeLiquidMake').value)">
    </br>
    Use <span id="coffeeBeanUse"> . . . </span>grams of coffee beans to make <span id="coffeeLiquidFinal"> . . . </span>.
    <br/>
</form>

应用程序/资产/ Javascript角/ grams_calc.js

function finalCoffee(){ 
  document.getElementById("coffeeLiquidFinal").innerHTML
    = document.getElementById("coffeLiquidMake").value;
};

function calcbrew(amount){
  amount=parseFloat(amount);
  var brewCalc = 5 * amount;
  document.getElementById("coffeeBeanUse").innerHTML=brewCalc;
};

我在app / layouts / application.html.erb文件中包含了这个:

<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

2 个答案:

答案 0 :(得分:0)

我在您的代码中发现了一些错误。

首先,您的第二个 br 标记,您使用</br>代替<br/>

然后,你得到的错误:

  

TypeError:null不是一个对象(评估&#39; document.getElementById(&#34; coffeeLiquidMake&#34;)。value&#39;)

这是因为您在 finalCoffee 功能中只有一个 e 写了 coffeeLiquidMake

另外,在你的JS中,你的 calcBrew 函数都是小写的,但在你的HTML中,你用大写字母&#34; B&#34;来调用它。

我希望这可以帮助你!!

&#13;
&#13;
function finalCoffee(){ 
  document.getElementById("coffeeLiquidFinal").innerHTML
    = document.getElementById("coffeeLiquidMake").value;
};

function calcBrew(amount){
  amount=parseFloat(amount);
  var brewCalc = 5 * amount;
  document.getElementById("coffeeBeanUse").innerHTML=brewCalc;
};
&#13;
<form name="grams_calc">
    <label for="coffee">How much coffee (grams) do you want to make?</label><br/>
    <input type="text" id="coffeeLiquidMake" placeholder="One cup = 300 grams." onChange="finalCoffee()" style="width: 250px">grams.
    <br/>
    <input type="button" value="Give Me Coffee!" onClick="calcBrew(document.getElementById('coffeeLiquidMake').value)">
    <br/>
    Use <span id="coffeeBeanUse"> . . . </span>grams of coffee beans to make <span id="coffeeLiquidFinal"> . . . </span>.
    <br/>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

您拼写错误coffeeLiquidMakecoffeLiquidMake。您拼写coffee错误