设置变量if ... then javascript

时间:2012-07-02 19:18:45

标签: javascript html function variables toggle

我正在尝试设置变量并将其上传到我的数据库,具体取决于页面上显示的文本。我正在使用一个简单的if ...然后在javascript中,它说变量是未定义的。还有另一种设置变量的方法吗?

<script type="text/javascript">
oldTextAry = new Array();
function changeText (fieldObj, newTexStr) {
    if (newTexStr == fieldObj.innerHTML) {
        fieldObj.innerHTML = oldTextAry[fieldObj.id];
        var waswere = 1;
    } else {
        oldTextAry[fieldObj.id] = fieldObj.innerHTML;
        fieldObj.innerHTML = newTexStr;
        var waswere = 2;
    }
}
function displayWasWere () {
        document.write(waswere);
}
</script>

HTML:

<HTML>
    <a href="#" onclick="changeText(this,'were');" id="text1link">was</a><br/>
    <a href="#" onClick="displayWasWere();" id="waswere" name="waswere">show variable</a>
</HTML>

2 个答案:

答案 0 :(得分:2)

waswere设为全局变量:

var waswere;
oldTextAry = new Array();
function changeText (fieldObj, newTexStr) {
    if (newTexStr == fieldObj.innerHTML) {
        fieldObj.innerHTML = oldTextAry[fieldObj.id];
        waswere = 1;
    } else {
        oldTextAry[fieldObj.id] = fieldObj.innerHTML;
        fieldObj.innerHTML = newTexStr;
        waswere = 2;
    }
}
function displayWasWere () {
    document.write(waswere);
}

答案 1 :(得分:1)

您的变量在第一个函数的范围内定义。使变量成为全局变量,您应该准备好滚动。