未捕获的类型错误:projected.value未定义



我目前正试图使用JavaScript中的正则表达式构建一个查找和替换程序,但当我单击;去";按钮,它应该查找并替换给定的字符串,尽管目前我所要做的只是将找到的字符串打印到控制台上:

Uncaught TypeError: projected.value is undefined

这是代码:

<body>
<textarea name="input" id="inputText" cols="30" rows="10">
</textarea>
<p id="projectedText"></p>
<label for="find">Find: </label>
<input type="text" id="find">
<label for="replace">Replace: </label>
<input type="text" name="" id="replace">
<input type="button" value="Go" id="commit">
</body> 
document.getElementById("commit").onclick=findNreplace; //set up go button
//variables
var textToShow = document.getElementById("inputText");
var projected = document.getElementById("projectedText");
var toFind = document.getElementById("find").value;
var toReplace = document.getElementById("replace").value; 
// set up text area to project the input into the paragraph
textToShow.addEventListener('input',updateValue);
function updateValue(text) {
projected.textContent=text.target.value;
}
// replace function
function findNreplace() {
var regex = /toFind/;
var found = projected.value.match(regex);
console.log(found);
}

我错过了什么?

<p>元素没有value属性,但您可以使用textContent属性更新它的方法来访问它的值。

为了匹配CCD_ 4输入的值;toFind"字符串,则需要使用正则表达式中的变量。

function findNreplace() {
var regex = new RegExp(toFind, 'g');
var found = projected.textContent.match(regex);
console.log(found);
}

您也可以直接重用输入值:

function findNreplace() {
var regex = new RegExp(toFind, 'g');
var found = textToShow.value.match(regex);
console.log(found);
}

如果您想获得函数中输入的当前值,而不是在脚本加载时仅获得初始值,则还需要更改元素选择器:

var toFind = document.getElementById("find");
var toReplace = document.getElementById("replace");

更新函数以获得调用时输入的当前值:

function findNreplace() {
var regex = new RegExp(toFind.value, 'g');
var found = textToShow.value.match(regex);
console.log(found);
}

在这行的末尾"var projected=document.getElementById("projectedText"(;写入值

最新更新