我试图在textarea中高亮显示字符串/文本,然后将其包裹在自定义标记周围。
我现在可以很容易地获得突出显示的文本,我可以将其包裹在标签周围并提醒()但我无法在textarea中替换它。
这是我工作的FIDDLE(https://jsfiddle.net/dftLu6ax/)
这是我的Javascript / jQuery代码:
$('#showSelected').on('click', function(){
function getInputSelection(elem){
if(typeof elem != "undefined"){
s=elem[0].selectionStart;
e=elem[0].selectionEnd;
return elem.val().substring(s, e);
}else{
return '';
}
}
var text = getInputSelection($("#details"));
var link = prompt("Please enter your URL", "");
if (link != null) {
var str = document.getElementById("details").value;
var res = str.replace(text, "<a onclick='somevariable goes here' href=''>"+text+"</a>");
alert(res);
/*document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";*/
}
});
和我简单的HTML:
<input type="button" id="showSelected" value="Insert Link">
<textarea class="form-control" rows="5" id="details" name="details"></textarea>
有人可以就此提出建议吗?
提前致谢。
答案 0 :(得分:2)
因为你在textarea里面得到了文字:
document.getElementById("details").value
您可以使用相同的方法设置更新的值:
function getInputSelection(elem){
if(typeof elem != "undefined"){
s=elem[0].selectionStart;
e=elem[0].selectionEnd;
return elem.val().substring(s, e);
}else{
return '';
}
}
$(function () {
$('#showSelected').on('click', function(){
var text = getInputSelection($("#details"));
var link = prompt("Please enter your URL", "");
if (link != null) {
var str = document.getElementById("details").value;
var res = str.replace(text, "<a onclick='somevariable goes here' href=''>"+text+"</a>");
//THIS LINE
document.getElementById("details").value = res;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="showSelected" value="Insert Link">
<textarea class="form-control" rows="5" id="details" name="details"></textarea>
答案 1 :(得分:1)
使用$("#details").val(res)
代替
$('#showSelected').on('click', function(){
function getInputSelection(elem){
if(typeof elem != "undefined"){
s=elem[0].selectionStart;
e=elem[0].selectionEnd;
return elem.val().substring(s, e);
}else{
return '';
}
}
var text = getInputSelection($("#details"));
var link = prompt("Please enter your URL", "");
if (link != null) {
var str = document.getElementById("details").value;
var res = str.replace(text, "<a onclick='somevariable goes here' href=''>"+text+"</a>");
$("#details").val(res);
/*document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";*/
}
});