我正在尝试获取一个文本框来更改 div 中的文本,如果添加方括号,我希望在文本周围添加一个跨度以使文本变为绿色。这是到目前为止我的代码:
function greenText() {
var textAreaText = $('#textarea').val();
var replacedText = textAreaText.replace("[", "<span style='color:green'>").replace("]", "</span>");
$('#preview').html(replacedText);
}
$(function() {
greenText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="preview" style="height: 4em; background-color:#eee; padding:10px;"></div>
<textarea id="textarea" rows="4" cols="50" onchange="greenText();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
At w3schools.com you will learn how to [make a website].
</textarea>
greenText
函数在页面加载时起作用,但是当我在括号中添加更新preview
时div 它将方括号打印到页面而不是 span 标签。有谁知道为什么该函数不替换文本吗?
最佳答案
对于字符串内的多次替换,您需要使用RegEx
:
function greenText() {
var textAreaText = $('#textarea').val();
var replacedText = textAreaText.replace(/\[/g, "<span style='color:green'>").replace(/\]/g, "</span>");
$('#preview').html(replacedText);
}
$(function() {
greenText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="preview" style="height:400px; background-color:#eee; padding:40px;"></div>
<textarea id="textarea" rows="4" cols="50" onchange="greenText();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();">
At w3schools.com you will learn how to [make a website].
</textarea>
关于jquery - 替换这个功能好像不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50466411/