JS onclick和jQuery .click之间的区别

时间:2015-06-05 15:20:01

标签: javascript jquery regex

我尝试了两种不同的方法来调用onclick函数。 像这样:

<input type="button" value="G" id="gras"></input>
<input type="button" value="I" onclick="insertTag('&lt;italique&gt;', '&lt;/italique&gt;', 'textarea')" />

并且像这样:

$("#gras").on("click", function() {
insertTag("&lt;gras&gt;", "&lt;/gras&gt;", "textarea"); });

只有第一个正在运作。 这是我的正则表达式:

field = field.replace(/&/g, '&amp;');
field = field.replace(/</g, '&lt;').replace(/>/g, '&gt;');
field = field.replace(/\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');

field = field.replace(/&lt;gras&gt;([\s\S]*?)&lt;\/gras&gt;/g, '<strong>$1</strong>');
field = field.replace(/&lt;italique&gt;([\s\S]*?)&lt;\/italique&gt;/g, '<em>$1</em>');

谢谢!

1 个答案:

答案 0 :(得分:-2)

这是JS:

$(document).ready(function () {
	$("#gras").on("click", function() {
		insertTag("&lt;gras&gt;, &lt;/gras&gt;, 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, '&amp;');
	field = field.replace(/</g, '&lt;').replace(/>/g, '&gt;');
	field = field.replace(/\n/g, '<br />').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');	
	field = field.replace(/&lt;gras&gt;([\s\S]*?)&lt;\/gras&gt;/g, '<strong>$1</strong>');
	field = field.replace(/&lt;italique&gt;([\s\S]*?)&lt;\/italique&gt;/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('&lt;italique&gt;', '&lt;/italique&gt;', '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>