我尝试了两种不同的方法来调用onclick函数。 像这样:
<input type="button" value="G" id="gras"></input>
<input type="button" value="I" onclick="insertTag('<italique>', '</italique>', 'textarea')" />
并且像这样:
$("#gras").on("click", function() {
insertTag("<gras>", "</gras>", "textarea"); });
只有第一个正在运作。 这是我的正则表达式:
field = field.replace(/&/g, '&');
field = field.replace(/</g, '<').replace(/>/g, '>');
field = field.replace(/\n/g, '<br />').replace(/\t/g, ' ');
field = field.replace(/<gras>([\s\S]*?)<\/gras>/g, '<strong>$1</strong>');
field = field.replace(/<italique>([\s\S]*?)<\/italique>/g, '<em>$1</em>');
谢谢!
答案 0 :(得分:-2)
这是JS:
$(document).ready(function () {
$("#gras").on("click", function() {
insertTag("<gras>, </gras>, textarea");
});
});
function insertTag(startTag, endTag, textareaId, tagType) {
var field = document.getElementById(textareaId);
var scroll = field.scrollTop;
field.focus();
var startSelection = field.value.substring(0, field.selectionStart);
var currentSelection = field.value.substring(field.selectionStart, field.selectionEnd);
var endSelection = field.value.substring(field.selectionEnd);
field.value = startSelection + startTag + currentSelection + endTag + endSelection;
field.focus();
field.setSelectionRange(startSelection.length + startTag.length, startSelection.length + startTag.length + currentSelection.length);
}
function preview(textareaId) {
var field = textareaId.value;
field = field.replace(/&/g, '&');
field = field.replace(/</g, '<').replace(/>/g, '>');
field = field.replace(/\n/g, '<br />').replace(/\t/g, ' ');
field = field.replace(/<gras>([\s\S]*?)<\/gras>/g, '<strong>$1</strong>');
field = field.replace(/<italique>([\s\S]*?)<\/italique>/g, '<em>$1</em>');
document.getElementById("previewDiv").innerHTML = field;
console.log(field);
}
var area = document.getElementById("textarea");
preview(area);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>WYSIWYG</title>
</script>
</head>
<body>
<div id="main">
<div>
<p>
<input type="button" value="G" id="gras"></input>
<input type="button" value="I" onclick="insertTag('<italique>', '</italique>', 'textarea')" />
</p>
</div>
<textarea id="textarea" cols="150" rows="10"></textarea>
<div id="previewDiv"></div>
</div>
<script src="jQuery.js"></script>
<script src="wysiwyg.js"></script>
</body>
</html>