请问我有这个javascript代码我想用bbcode例子[b] peter [/ b]来包装所选文本但不适合我,任何人都可以修复它或者让我知道这样做吗?
<script type="text/javascript">
function bbcoder(){
var old = "";
var value = textarea.value;
var startPos = textarea.selectionStart;
var endPos = textarea.selectionEnd;
var selectedText = value.substring( startPos, endPos );
function bbbold(){
var old=document.getElementsByName("blog_body")[0].value;
document.getElementsByName("blog_body")[0].value=old+"[b]"+ selectedText +"[/b]";
}
function bbitalic(){
var old=document.getElementsByName("blog_body")[0].value;
document.getElementsByName("blog_body")[0].value=old+"[i]"+ selectedText +"[/i]";
}
function bbunder(){
var old=document.getElementsByName("blog_body")[0].value;
document.getElementsByName("blog_body")[0].value=old+"[u]"+ selectedText +"[/u]";}
function bbquote(){
var old=document.getElementsByName("blog_body")[0].value;
document.getElementsByName("blog_body")[0].value=old+"[quote]"+ selectedText +"[/quote]";
}
</script>
这是html表单
<div id="editor">
<ul id="buttons">
<li><a href="javascript:void(0);" onclick="bbbold()">B</a></li>
<li><a href="javascript:void(0);" onclick="bbunder()"><u>U</u></a></li>
<li><a href="javascript:void(0);" onclick="bbitalic()">I</a></li>
<li><a href="javascript:void(0);" onclick="bbquote()">""</a></li>
</ul>
<form id="editor-form" action="" method="post">
<div>
<textarea id="blog_body" name="blog_body" rows="15" cols="20" placeholder="Use editor buttons on selected text"></textarea>
</div>
<p><input type="submit" value="Save"></p>
</form>
</div>
答案 0 :(得分:0)
更新:jsFiddle 请注意,我无法在jsFiddle中使用函数内部函数,因此必须将其移出。
尝试以下代码
function bbcoder(code) {
try {
var old = "";
var textarea = document.getElementsByName("blog_body")[0];
var value = textarea.value;
var startPos = textarea.selectionStart;
var endPos = textarea.selectionEnd;
var selectedText = value.substring(startPos, endPos);
switch (code) {
case 'B':
bbbold();
break;
case 'U':
bbunder();
break;
case 'I':
bbitalic();
break;
case 'Q':
bbquote();
break;
default:
alert('Invalid argument');
break;
}
function bbbold() {
var old = textarea.value;
textarea.value = old.replaceBetween(startPos, endPos, "[b]" + selectedText + "[/b]");
}
function bbitalic() {
var old = textarea.value;
textarea.value = old.replaceBetween(startPos, endPos, "[i]" + selectedText + "[/i]");
}
function bbunder() {
var old = textarea.value;
textarea.value = old.replaceBetween(startPos, endPos, "[u]" + selectedText + "[/u]");
}
function bbquote() {
var old = textarea.value;
textarea.value = old.replaceBetween(startPos, endPos, "[quote]" + selectedText + "[/quote]");
}
} catch (e) {
alert(e.toString());
}
}
//http://stackoverflow.com/questions/14880229/how-to-replace-a-substring-between-two-indices
String.prototype.replaceBetween = function (start, end, what) {
return this.substring(0, start) + what + this.substring(end);
};