我编写了一个简短的jquery方法,在文本框的keypress事件中应该将文本框内容更改为大写。该方法触发并显示警报,但文本的大小写从不变为大写。
这是jquery方法
$("#TestText").bind('keyup', function (e) {
var mytext = $("#TestText").val();
$(mytext).text($(mytext).text().toUpperCase());
alert(mytext);
$("#TestText").val() = $(mytext);
});
任何人都可以帮助我并告诉我出了什么问题吗?
答案 0 :(得分:4)
要引用收到该事件的元素,请使用this
。
你正在做的是拍摄文字,并将其包裹在$()
中,就像你选择一个元素一样。
然后您通过.val()
使用了= $(mytext)
的不当使用。
jQuery的.val()
方法有两个用途。没有参数,获取值。使用参数,设置值。
$("#TestText").bind('keyup', function (e) {
// get the value of the input
var mytext = $(this).val();
// set the value of the input
$(this).val(mytext.toUpperCase());
});
编辑:缓存重用的jQuery对象总是一个好主意。
$("#TestText").bind('keyup', function (e) {
var $th = $(this);
// get the value of the input
var mytext = $th.val();
// set the value of the input
$th.val(mytext.toUpperCase());
});
答案 1 :(得分:1)
使用val()
代替text()
:
$("#TestText").bind('keyup', function (e) {
$(this).val($(this).val().toUpperCase());
});
答案 2 :(得分:0)
我想这应该这样做
$("#TestText").bind('keyup', function (e) {
$(this).val($(this).val().toUpperCase());
});
答案 3 :(得分:0)
这应该有效:
$("#TestText").bind('keyup', function (e) {
$("#TestText").val($(this).val().toUpperCase());
});
但我会使用css属性text-transform并将其设置为
#TestText {
text-transform:uppercase;
}