getElementById()没有返回正确的字符串

时间:2015-07-17 19:32:51

标签: javascript textarea getelementbyid

我正在尝试从textarea中获取文本并返回一些东西,但它没有返回任何内容,没有字符串..当我在textarea中输入一个字符串并单击按钮时,它仍然没有返回任何内容。

var name;
name = document.getElementById('username').value;

function action() {
document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
console.log("Working");
}

HTML:

<textarea rows="4" cols="50" id="username" placeholder="Enter your username here!"></textarea> <br />
        <button id="submit" onClick="action()">Submit</button>
        <br />
        <img id="theIMG"></img>

3 个答案:

答案 0 :(得分:1)

在执行代码时,值为&#34;&#34;只要。并且它不会改变,无论您是否更改了html中的值,因为您没有在脚本中更新它。因此,您需要将代码更新为以下

function action() {
    var name = document.getElementById('username').value;
    document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
    console.log("Working");
}

答案 1 :(得分:1)

您应该在NewLog方法中调用getElementById - action在文本框更改时不会继续存在:

value

答案 2 :(得分:1)

您需要在函数本身中定义名称,如下所示:

var name;


function action() {
name = document.getElementById('username').value;
document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
console.log("Working");
}