简体   繁体   English

以数组形式获取 TextArea 输入值,并使用 forEach 循环 console.log 中的值使用 Javascript

[英]Get TextArea Input Value in form of array and forEach loop the value in console.log Using Javascript

function someSample() {
    let textAreaTag = document.getElementById('textAreaId');
    let textAreaVal = textAreaTag.value;
    let textAreaSplit = textAreaVal.split('');
    
    textAreaTag.addEventListener('input', () => {
        textAreaSplit.forEach((val, ind) => {
            console.log(val);
        });
    }); 
}   

someSample();

在此处输入图像描述

There is on textarea input field, so first i gave a addEventListener while typing any text in textarea the value of text area text should get forEach Loop and the loop array should show inside console.log.. But now the loop array is showing blank or undefined.在textarea输入字段上,所以首先我在textarea中键入任何文本时给了一个addEventListener,文本区域文本的值应该得到forEach Loop并且循环数组应该显示在console.log中..但是现在循环数组显示空白或不明确的。

All you need to do is move 2 lines of code.您需要做的就是移动 2 行代码。

someSample is getting the initial value of the textarea, which will be an empty string. someSample 正在获取文本区域的初始值,它将是一个空字符串。 Then it is adding an event listener, which will fire every time the input changes in the text area.然后它添加了一个事件侦听器,每次文本区域中的输入更改时都会触发该事件侦听器。 The problem is that you're not updating textAreaVal with every input change, and you're simply using the initial empty string.问题是您没有在每次输入更改时更新 textAreaVal,而只是使用初始的空字符串。 On input change, you need to get the value, split the value, then loop through.在输入更改时,您需要获取值、拆分值,然后循环。 someSample should look like this: someSample 应该是这样的:

function someSample() {
    let textAreaTag = document.getElementById('textAreaId');
    
    textAreaTag.addEventListener('input', () => {
        let textAreaVal = textAreaTag.value;
        let textAreaSplit = textAreaVal.split('');
        textAreaSplit.forEach((val, ind) => {
            console.log(val);
        });
    }); 
}   

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

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