如何在javascript中调用函数单击它只运行一次

时间:2016-02-21 18:45:42

标签: javascript

<script>
var myValue = parseInt(12);
function fontresize(value){
var getval = parseInt(value);
var chngeval = myValue + getval;
localStorage.setItem("fontset", chngeval);
    document.getElementById("changefont").style.fontSize = chngeval + "px";
}

window.onload = function(){
    var allstorage = localStorage.fontset;

    if(allstorage != undefined || allstorage == ""){
    document.getElementById("changefont").style.fontSize = allstorage + "px";
    }

};

 <button onClick="fontresize('5')">+</button>

In是一个增加我的页面字体大小的代码,但问题是当页面加载时我只想运行一次我想在每次点击时调用一个函数我可以用java脚本来做。

3 个答案:

答案 0 :(得分:1)

您不会在函数内更新myValue的值,因此无论何时单击该按钮,计算出的字体大小始终12 + 5

按如下方式更新您的fontresize

function fontresize(value)
{
    var getval = parseInt(value),
        chngeval = myValue = (myValue + getval);

    localStorage.setItem("fontset", chngeval);
    document.getElementById("changefont").style.fontSize = chngeval + "px";
}

jsFiddle Demo

顺便说一下,你第一行的parseInt()是多余的; 12已经是整数,因此您只需使用:

var myValue = 12;

答案 1 :(得分:0)

Plunker

var fontSize = 0;
document.getElementById('btn').addEventListener('click', function() {
  fontresize(fontSize+=5);
});

答案 2 :(得分:0)

尝试在chngeval之外移动fontresize,使用+=运算符递增chngeval;在检查null

时,还会将undefined替换为localStorage
var myValue = 12, chngeval = 0;

function fontresize(value) {
  var getval = parseInt(value);
  chngeval += myValue + getval;
  localStorage.setItem("fontset", chngeval);
  console.log(localStorage.getItem("fontset"))
  document.getElementById("changefont").style.fontSize = chngeval + "px";
}

window.onload = function() {
  var allstorage = localStorage.fontset;

  if (allstorage !== null || allstorage === "") {
    document.getElementById("changefont").style.fontSize = allstorage + "px";
  }

};

plnkr http://plnkr.co/edit/9eSDtDEvUxhPjqa2h0Z0?p=preview