我试图设置一个变量并将其上传到数据库中,具体取决于页面上显示的文本。我正在使用一个简单的if ... then在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>

最佳答案

使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);
}

07-24 17:51