Javascript 从textarea don';不会显示在HTML页面上
我在想一些有趣的事情。我想创建一个页面来计算文本区域中存在多少单词。当用户点击“计数”按钮时,下面会显示存在多少单词。我尝试了一些东西,但在我的html页面上没有结果Javascript 从textarea don';不会显示在HTML页面上,javascript,html,Javascript,Html,我在想一些有趣的事情。我想创建一个页面来计算文本区域中存在多少单词。当用户点击“计数”按钮时,下面会显示存在多少单词。我尝试了一些东西,但在我的html页面上没有结果 var form=document.querySelector(“表单”); var counted=document.querySelector(“.counted”); 表.addEventListener(“计数”,函数(ev){ ev.preventDefault(); countWords(); },假); //var
var form=document.querySelector(“表单”);
var counted=document.querySelector(“.counted”);
表.addEventListener(“计数”,函数(ev){
ev.preventDefault();
countWords();
},假);
//var countWords=string=>string.split(“”).length;
//countWords(textarea.value);
//document.querySelector(“#counted”).value=countWords(字符串);
//函数countWords(){
//var textarea=document.querySelector(“textarea”).value;
//
//document.querySelector(“#textarea”).value=textarea.split(“”).length;
//document.querySelector(“.counted”).innerHTML+=“此文本中有“+textarea+”个单词。”;
// }
函数countWords(){;
字符串=document.querySelector(“#textarea”).value;
string=string.replace(/(^\s*)|(\s*$)/gi,“”);
string=string.replace(/[]{2,}/gi,“”);
string=string.replace(/\n/,“\n”);
document.querySelector(“#counted”).value=string.split(“”).length;
}
数一数有多少个单词
计数
您应该
- 添加
事件,而不是onSubmit
(无效),以及onCount
- 设置HTML元素的
或.innerText
,而不是.innerHTML
,如果它不是.value
或
:
var form=document.querySelector(“表单”);
var counted=document.querySelector(“.counted”);
表格.附录列表(“提交”,功能(ev){
ev.preventDefault();
countWords();
},假);
//var countWords=string=>string.split(“”).length;
//countWords(textarea.value);
//document.querySelector(“#counted”).value=countWords(字符串);
//函数countWords(){
//var textarea=document.querySelector(“textarea”).value;
//
//document.querySelector(“#textarea”).value=textarea.split(“”).length;
//document.querySelector(“.counted”).innerHTML+=“此文本中有“+textarea+”个单词。”;
// }
函数countWords(){;
字符串=document.querySelector(“#textarea”).value;
string=string.replace(/(^\s*)|(\s*$)/gi,“”);
string=string.replace(/[]{2,}/gi,“”);
string=string.replace(/\n/,“\n”);
document.querySelector(“#counted”).innerText=string.split(“”).length;
}
数一数有多少个单词
计数
window.onload=(函数(){
var count=document.querySelector(“计数”);
var counted=document.querySelector(“.counted”);
表单。添加的EventListener(“单击”,函数(ev){
ev.preventDefault();
countWords();
},假);
函数countWords(){
var string=document.querySelector(“#textarea”).value;
string=string.replace(/(^\s*)|(\s*$)/gi,“”);
string=string.replace(/[]{2,}/gi,“”);
string=string.replace(/\n/,“\n”);
console.log(字符串);
document.querySelector(“#counted”).innerHTML=string.split(“”).length;
}
})();代码>
数一数有多少个单词
计数
定义按钮类型=按钮
计数
下面是onclick函数:
function countWords(){;
string = document.querySelector("#textarea").value;
string = string.replace(/(^\s*)|(\s*$)/gi,"");
string = string.replace(/[ ]{2,}/gi," ");
string = string.replace(/\n /,"\n");
var count=document.querySelector("#counted").value;
count= string.split(' ').length;
alert(count);
}
它不会返回文本区域中有多少单词。。。始终显示1@MiguelCruz这对我有用。。。你使用什么浏览器?请解释,错误是什么,你更改了什么。我已经添加了解释。