使用jquery用包装某个单词
我有以下div
:
客户端可以编写SQL
查询。 我试图做的是用一个span
击中Space后用客户端输入的单词,并根据输入的单词给这个跨度指定一个class
:
例
如果客户端类型select
我需要在div中包装这样的选择单词:
SELECT emp_name
CSS
.select{color:blue ;text-transform:uppercase;}
这与jsFiddle
非常相似。 我怎样才能做到这一点?
这是我到目前为止所尝试的: jsFiddle
$(function(){ $('div').focus() ; $('div').keyup(function(e){ //console.log(e.keyCode) ; if(e.keyCode == 32){ var txt = $('div').text() ; var x = 'SELECT' ; $('div:contains("'+x+'")').wrap("") ; if(txt == 'SELECT'){ console.log('found') ; // why This Doesn't do any thing ? } } }); });
我做了一个概念validation,并对你原来的东西进行了一些修改。 见下文,
演示: http : //jsfiddle.net/cgy69/
$(function() { $('div').focus(); var x = ['SELECT', 'WHERE', 'FROM']; $('div').keyup(function(e) { //console.log(e.keyCode) ; if (e.keyCode == 32) { //using .text() remove prev span inserts var text = $.trim($(this).text()).split(' '); $.each(text, function(i, v) { $.each(x, function(j, xv) { if (v.toUpperCase() === xv) { text[i] = '' + v + ''; } }); }); $(this).html(text.join(' ') + ' '); setEndOfContenteditable(this); } }); function setEndOfContenteditable(contentEditableElement) { var range, selection; if (document.createRange) //Firefox, Chrome, Opera, Safari, IE 9+ { range = document.createRange(); //Create a range (a range is a like the selection but invisible) range.selectNodeContents(contentEditableElement); //Select the entire contents of the element with the range range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start selection = window.getSelection(); //get the selection object (allows you to change selection) selection.removeAllRanges(); //remove any selections already made selection.addRange(range); //make the range you have just created the visible selection } else if (document.selection) //IE 8 and lower { range = document.body.createTextRange(); //Create a range (a range is a like the selection but invisible) range.moveToElementText(contentEditableElement); //Select the entire contents of the element with the range range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start range.select(); //Select the range (make it the visible selection } } });
你将进一步扩展这个处理
-
退格 -
以前插入的HTML内容 -
光标位置部分完成,在中间编辑仍然会弄乱插入符号。
和更多..
从一个contenteditable
元素开始,我们可以通过直接在其innerHtml
上操作来替换我们需要的标记:
$('#query-container').on('keyup', function(e){ var $this = $(this); //(?!\<\/b\>) negative lookahead is used so that anything already wrapped //into a markup tag would not get wrapped again $this.html($this.html().replace(/(SELECT|UPDATE|DELETE)(?!\<\/b\>)/gi, '$1')); setEndOfContenteditable(this); });
IMO这是一个更具可读性的选择。 添加上一个答案中的rangeselect方法,我们有一个工作小提琴