Including javascript to google sites

半城伤御伤魂 提交于 2019-12-03 19:34:25

问题


I'm trying to include a simple javascript to Google Sites but I get nothing when pressing the button. I put the code inside an HTML Box. The code works perfectly when tested locally. Here is my code:

<script>
  function calcul(){
    x = parseFloat(document.getElementById("value1").value);
    y = parseFloat(document.getElementById("value2").value);
    document.getElementById("answer").innerHTML=x+y;
  }
</script>

<form action="" id="nothing">
  <input type="text" id="value1">
  <input type="text" id="value2">
<input type="button" value="Calculate" id="but" onclick="calcul()" />

<p id="answer"></p>

Is there something I forgot to make it work?


回答1:


Google Sites changes your entire script. You have to be a bit more careful writing JavaScript.

Adding var in front of every variable will fix your problem:

<script>
  function calcul(){
    var x = parseFloat(document.getElementById("value1").value);
    var y = parseFloat(document.getElementById("value2").value);
    document.getElementById("answer").innerHTML=x+y;
  }
</script>

<form action="" id="nothing">
  <input type="text" id="value1">
  <input type="text" id="value2">
  <input type="button" value="Calculate" id="but" onclick="calcul()" />
</form>

<p id="answer"></p>

This will work ;-)




回答2:


Google Sites will filter out operations it considers unsafe. Some details here, but was unable to find official documentation with quick search.

As another answer mentions, your variables need var declarations. This is required because without this, the variables will become global to the window, and potentially could be used to escape whatever sandbox Google is putting around the sites javascript support, potentially causing security concerns.

So to fix:

var x = parseFloat(document.getElementById("value1").value);
var y = parseFloat(document.getElementById("value2").value);


来源:https://stackoverflow.com/questions/14780838/including-javascript-to-google-sites

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!