简体   繁体   English

为什么textarea.value返回“未定义”? (使用本机Javascript)

[英]Why is textarea.value returning “undefined”? (using Native Javascript)

This is really simple but I just cant figure out what is Wrong. 这真的很简单,但我无法弄清楚什么是错误的。

I got a div , a textarea , a button . 我得到了一个div ,一个textarea ,一个button

I want to use "Native-Javascript" coz lately i have been using jQuery alot and I want to go Native on this basic thing. 我最近想使用“ Native-Javascript”,因为我一直在使用jQuery ,因此我想在此基本功能上使用Native。

The Aim is to get the contents of the enter code here textarea transfered to the div and have the same logged in the console on button 's click . 目的是将enter code here的内容从enter code here textarea转移到div并在click button时在console记录相同的内容。

See my Codes: 查看我的代码:

Javascript: Javascript:

function text_func (){
    var btn = document.getElementsByTagName('button'),
        div_out = document.getElementsByTagName('div');
        txt_a = document.getElementsByTagName('textarea');

    console.log(txt_a.value);// This Logs undefined :: WHY?

        //return;
        btn[0].addEventListener('click',btn_click,false);

        function btn_click(){

            console.log(txt_a.value)//  This also logs undefined.. Why again?
            div_out.innerHTML = txt_a.value;

            }

    }

window.onload = function(){

    text_func();    

    }

HTML: HTML:

<div id="myDiv" style="width:300px; border:1px solid #ccc; height:100px; padding:10px;"></div>

<textarea style="width:300px; border:1px solid #ccc; height:100px; padding:10px;"></textarea>

<button>Go</button>

What I'm I doing wrong?.... 我在做什么错?....

See Fiddle: http://jsfiddle.net/3urm9/ Any Suggestion is highly appreciated. 参见Fiddle: http : //jsfiddle.net/3urm9/任何建议均受到高度赞赏。

You can try: 你可以试试:

console.log(txt_a[0].value)

Notice the [0] 注意[0]

getElementsByTagName

That returns an array (actually a NodeList) of elements. 这将返回一个元素数组 (实际上是一个NodeList)。
Arrays don't have a value property. 数组没有value属性。

You probably want to get one of the elements from the array. 您可能想要从数组中获取元素之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM