为什么给定的代码没有将任何文本转换为大写?

时间:2014-04-16 19:13:45

标签: javascript jquery html

<script> 
var a = document.getElementById("text").value;
function toupper()
{
    var mystring = new String(a);
    document.write(a.toUpperCase());
}
</script>

**HTML**
<input type="text" id="text" name="text" />
<input type="button" id="clickme" value="clickme" name="click" onclick="toupper();"/>

为什么变量&#34; a&#34;无法在&#34; toupper&#34;中访问功能

5 个答案:

答案 0 :(得分:1)

var a拉入功能&amp;你不必写new String(a)

function toupper() {
    var a = document.getElementById("text").value;
    document.write(a.toUpperCase());
}

http://jsfiddle.net/Fn4Ns/3/

答案 1 :(得分:0)

语句var a = document.getElementById("text").value的执行失败,因为当它被执行时,id值为text的元素尚未被解析,即不存在。您需要在函数内部使用document.getElementById("text"),或者在元素存在的位置使用{{1}}。

答案 2 :(得分:0)

问题是你正在尝试执行

var a = document.getElementById("text").value;
在文档加载完毕之前

请尝试以下它应该工作。

var a;
        document.addEventListener('DOMContentLoaded', function() {
            a = document.getElementById("text").value;     
        });

        function toupper()
        {
            var mystring = new String(a);
            document.write(a.toUpperCase());
        }

变量a在外部声明,因此可以在两个作用域回调中访问文档就绪和toupper函数。 在确保已加载页面(DOM)之后获取元素值

答案 3 :(得分:0)

您需要在每次函数调用时重新检索对文本字段的引用。

DEMO

var writeNewLine = function(text) {
    var addChild = function(node) {
        window.document.body.appendChild(node);
    };
    addChild(document.createElement('br'));
    addChild(document.createTextNode(text.toUpperCase()));
};

window.toupper = function() {
    var mystring = document.getElementById("text").value;
    writeNewLine(mystring.toUpperCase());
}

答案 4 :(得分:0)

这会奏效。在文本框加载之前分配了值

function toupper(){ var a = document.getElementById("text").value; document.write(a.toUpperCase()); }

相关问题