How can I implement this interaction model with jQuery?
With jQuery, I'm interested in creating the following interaction model.
开发者_StackOverflow中文版When a user types in the page, anytime jQuery notices three !, "!!!" typed in a row, to be able to do something about it.
After noticing three !, "!!!", wrap the previous sentence (finding the last period from the location the user is currently typing and wrapping a
<span class=Important>
How can I do this?
This should work. I've set it up as a live event handler (so that it works for elements dynamically added to the page), but you could use the exact same function as a normal keyup handler on any textarea
or input
element as well.
It checks to see whether the element's current value ends with !!!
and if so performs the replacement, both using simple regular expressions.
$("input,textarea").live("keyup", function() {
var $this = $(this);
var value = $this.val();
if (/!!!$/.test(value)) {
$this.val(value.replace(/(\.?)([^.]+?\.?\s*)!!!$/, '$1<span class="important">$2</span>'));
}
});
As much as I am loathe to say that jQuery isn't good for something - perhaps this kind of logic is better handled on the server. Unless they are typing in an HTML editor where the newly inserted span tags are invisible to the user, it may be a little disconcerting to be typing in a textarea/textbox and suddenly see a bunch of HTML inserted into my comment.
精彩评论