如何使用jQuery 1.4.3及更高版本按值选择输入

H1D*_*H1D 25 jquery

使用jQuery 1.4.2和许多以前的版本,可以选择这样的输入:

$('input[value=test]')
Run Code Online (Sandbox Code Playgroud)

但是1.4.3及更高版本这个选择器不起作用=(有没有办法在较新版本的jQuery中按值选择?

Ale*_*lex 39

$('input[value="test"]') 应该工作正常......

编辑

您可以尝试使用if语句,例如:

$("input").keyup(function(e) { 
    if (this.value == 'foo'){
        $(this).css('backgroundColor','red');
    }
    else if (this.value == 'bar'){
        $(this).css('backgroundColor','green');
    }
    else $(this).css('backgroundColor','white');
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/ajthomascouk/HrXVS/


dal*_*ege 22

据我所知,在较新的jQuery版本中,您可以通过" value "属性选择INPUT元素,但不能通过当前的.value属性选择.

通过调用.val(),更改本机JS .value或直接用户输入来更改值时,不会更改HTML属性.在以前的版本中,选择器引用了当前值,而现在它们正确引用了HTML属性.

您可以使用以下代码选择当前值:

$('input').filter(function() { return this.value == 'test' });
Run Code Online (Sandbox Code Playgroud)


H1D*_*H1D 2

所以,解决办法就是在js中添加:

$('input').bind('keyup change',function() {
    $(this).attr('value',this.value)
});
Run Code Online (Sandbox Code Playgroud)

演示 - http://jsfiddle.net/VwVhD/28/

更新(2013 年 2 月 21 日)

多年后我实际上想出了这个:

jQuery('input,textarea').live('keyup change', function(e) {
    var ignore_codes = [16,9,33,34,36,35,45,38,40,37,39];//arrows and others
    if (e.keyCode && jQuery.inArray(e.keyCode, ignore_codes) < 0)//ignore this keyUps to let this keys work as expected
    {
        var cp = getCP(this);
        jQuery(this).attr('value', this.value);
        setCP(this,cp);
    }
    });
    function setCP(ctrl, pos){
        if(ctrl.setSelectionRange) {
            ctrl.focus();
            ctrl.setSelectionRange(pos,pos);
        } else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }
Run Code Online (Sandbox Code Playgroud)