How to make custom script into Jquery like plugin
I have writtern a script to limit the number of characters in the textarea, and the code is here
<script>
function limitchar(charcount, counterId, msgId)
{
var tex = document.getElementById(msgId).value;
var len = tex.length;
if(len > charcount)
{
alert("Content Limit Exceeded");
tex = tex.substring(0,charcount);
document.getElementById(msgId).value =tex;
return false;
}
document.getElementById(counterId).innerHTML = charcount-len;
}
</script>
I am calling the function as
<textarea name="txtar1" id="txtar1" onkeyup=limitchar('10','verid','txtar1')></textarea>
I dont want these kind of ugly function call, since my textareas are dynamically generated
Like Jquery, I want my function to be called like
$('txtar1').limitchar();
Is there anyother way to achieve th开发者_如何学运维is. Thanks Experts! in advance
ANSWER :
Thanks for andy rose. I used his approach. Here is my final code:
<script>
$(document).ready(function() {
$('#txtar1').keydown(function() {
limiter('10', 'verid' , this.id);
});
});
</script>
<textarea name="txtar1" id="txtar1"></textarea>
<span id="verid">10</span>
<script>
/* Will use as common.js */
function limiter(charcount,showcountid,msgId)
{
var tex = document.getElementById(msgId).value;
var len = tex.length;
if(len > charcount)
{
//alert("Content Limit Exceeded");
tex = tex.substring(0,charcount);
document.getElementById(msgId).value =tex;
return false;
}
document.getElementById(showcountid).innerHTML = charcount-len;
}
</script>
You might want to look at this blog entry from Mike Alsup in which he explains a pretty good pattern on how to develop a jQuery-Plugin. He also goes into very much details about further development and extending the basic plugin.
Rather than creating a new plugin why not use one of jQuery's key events:
$('txtar1').keydown(function() {
...stuff here
});
It's easy. Just do:
$.fn.limitchar = function () {
var $items = $(this);
};
$items
will be a jQuery object equivalent to $('txtar1')
.
精彩评论