无法通过javascript函数更改元素的值

时间:2020-04-15 06:37:50

标签: javascript html

因此,我尝试通过getElementById()调用函数来更改p元素。但是当我单击按钮时,什么也没有发生。

当我单击按钮时,应该将汽车品牌更改为字符串的长度,并添加兰博基尼。

代码如下:-

<html>
 <head>
   <script src="javascript_file.js" type="text/javascript"></script>
 </head>
  <body>

  <h1>strings and functions</h1>
  <p id="pFunction">hi</p>
  <button type="button" onclick="document.getElementById('pFunction').innerHTML = 'bye'">click!</button>

  <p id="slice">car brands</p>
  <button onclick="sliceF">Click it!</button>
 </body>

</html>

Js:-

function sliceF(){
   var cars = "bmw , lamborghini , toyota";
   var lengthCars = cars.length;
   var sliceCars = cars.slice(6 , 16);
   document.getElementById('slice').innerHTML = "the length of the string is " + lengthCars + "<br/>" + "the brand in the middle is " + sliceCars;
}

3 个答案:

答案 0 :(得分:0)

将“ sliceF”更改为“ sliceF()”

它现在可以正常工作吗?如果不起作用,请答复。

答案 1 :(得分:-1)

您忘记了函数调用的括号:

<html>
 <head>
   <script src="javascript_file.js" type="text/javascript"></script>
 </head>
  <body>

  <h1>strings and functions</h1>
  <p id="pFunction">hi</p>
  <button type="button" onclick="document.getElementById('pFunction').innerHTML = 'bye'">click!</button>

  <p id="slice">car brands</p>
  <button onclick="sliceF()">Click it!</button>
 </body>

</html>

https://jsfiddle.net/

答案 2 :(得分:-1)

我认为您只需要更改

   onclick="sliceF"

   onclick="sliceF()"