2010-07-28 32 views
0

我写了一个简短的jquery方法,在文本框的按键事件应该改变文本框内容为大写。该方法触发并显示警报,但文本的案例不会更改为大写。jquery方法运行但不改变文本框文本的情况

这里是jQuery的方法

$("#TestText").bind('keyup', function (e) { 
    var mytext = $("#TestText").val(); 
    $(mytext).text($(mytext).text().toUpperCase()); 
    alert(mytext); 
    $("#TestText").val() = $(mytext); 
}); 

谁能帮助我,告诉我出了什么问题?

回答

4

要引用收到该事件的元素,可以使用this

你在做什么取得的文字,并包装在$()就好像你选择一个元素。

然后,您通过做= $(mytext)来使用不当使用.val()

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

使用val(),而不是text()

$("#TestText").bind('keyup', function (e) { 
    $(this).val($(this).val().toUpperCase()); 
}); 
0

我想这应该这样做

$("#TestText").bind('keyup', function (e) { 
    $(this).val($(this).val().toUpperCase()); 
}); 
0

这应该工作:

$("#TestText").bind('keyup', function (e) { 
    $("#TestText").val($(this).val().toUpperCase()); 
}); 

,但我会用CSS属性text-transform并将其设置为

#TestText { 
    text-transform:uppercase; 
    } 
相关问题