jQuery函数 [英] Jquery Function
问题描述
我正在使用以下代码在文本区域上设置字符数.就我通过textarea ID而言,此解决方案工作正常.
I am using the below code to set the character count on a textarea. This solution is working fine as far as i am passing the textarea ID.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var charactersAllowed = 255; // this is picked from widget configuration
$("#charCount").html(charactersAllowed);
$("#message").keyup(function() {
$("#charCount").html(charactersAllowed - ($(this).val().length));
if($(this).val().length > charactersAllowed) {
this.value = this.value.substring(0, charactersAllowed);
$("#charCount").html(charactersAllowed - ($(this).val().length));
}
});
});
</script>
</head>
<body>
<textarea name="message" id="message" tabindex="4" rows="4" cols="35"></textarea>
<p class="character_limit">Character limit: <span id="charCount"></span></p>
</body>
</html>
我需要做的是将此功能包装在函数中,以便可以在任何输入元素上调用此函数. 我可以在函数名称中包装相同的代码,并在Textarea onchange()事件上调用相同的函数吗?
what i need to do is to wrap this functionality in function so that i can call this function on any input element. Can i wrap the same code inside a function name and call the same function on Textarea onchange() event?
请向我提供输入和&帮助重新编码此代码段.
Please provide me the inputs & help to recode this snippet.
谢谢 洛克希·亚达夫(Lokesh Yadav)
Thanks Lokesh Yadav
推荐答案
您可以将所需内容应用于任何文本区域:
You can apply what you have to any text area:
$(document).ready(function() {
limitTextBox("#message", "#charCount", 255);
});
function limitTextBox(box, charsDisplay, charactersAllowed) {
var $box = $(box),
$charsDisplay = $(charsDisplay);
$charsDisplay.html(charactersAllowed - ($box.val().length));
$box.keyup(function() {
$charsDisplay.html(charactersAllowed - ($box.val().length));
if($box.val().length > charactersAllowed) {
$box[0].value = $box[0].value.substring(0, charactersAllowed);
$charsDisplay.html(charactersAllowed - ($box.val().length));
}
});
}
...但是我可以强烈建议您不要这样做.相反,请看一下StackOverflow如何限制输入到文本框(例如注释)中.他们让您键入所需的任何内容,但实际上只有在您输入的范围内时,才可以保存您的评论.当人们键入内容时,内容会被截断,这会带来糟糕的用户体验.
...but can I strongly recommend that you don't do that. Look instead at how StackOverflow limits input into text boxes (such as comments). They let you type whatever you want, but only actually let you save your comment if you're within range. This truncating the content as people type makes for a terrible user experience.
离题:在您的原始函数中,有时您在jQuery实例上使用val()
,而其他时候在原始DOM元素上使用value
.我已经在上面保留了此内容,但您可能希望选择其中一个并在整个过程中使用它.
Off-topic: In your original function, sometimes you used val()
on a jQuery instance, other times you used value
on the raw DOM element. I've preserved that above, but you probably want to pick one or the other and use it throughout.
这篇关于jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!