Javascript不允许每次点击时更新静态变量

时间:2018-02-06 15:30:46

标签: javascript static

我试图在用户点击演示部分时每次都切换标记值。

我的印象是静态变量是myFunction.flag,并且每次更改时它都会在整个页面中保持不变...

<!DOCTYPE html>
<html>
<body>

<p>Search a string for "w3Schools", and display the position of the match:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "Visit W3Schools!"; 
    var n = str.search(/w3Schools/i);
    myFunction.flag = 1;
    if(myFunction.flag){
    document.getElementById("demo").innerHTML = myFunction.flag;
    myFunction.flag = 0;
   } else {
    document.getElementById("demo").innerHTML = myFunction.flag;
    myFunction.flag = 1;
    }
}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

每次点击都会创建一个新变量。

让它全球化。

<div id="drop" class="input-group">
    <span class="input-group-addon input-group-prepend"><i class="glyphicon glyphicon-picture"></i></span>
    <input type="text" class="form-control input-sx" disabled placeholder="Upload Image">
    <span class="input-group-btn input-group-append">
        <button class="browse btn btn-primary input-sx" type="button"><i class="glyphicon glyphicon-search"></i> Browse</button>
    </span>
</div>