简体   繁体   English

jQuery值属性选择器未返回正确的元素数

[英]jQuery value attribute selector not returning correct number of elements

I have a programme that generates a count after the key is up. 我有一个程序,在密钥启动后生成一个计数。 JQuery Code: JQuery代码:

$('.today').keyup(function() {
    var Presents = $('input[value="/"]:visible');
    $("#counter").html( "Present: " + Presents.length );
});

HTML: HTML:

<input type="text" id="1" name="1" class="today" value="/">
<input type="text" id="2" name="2" class="today" value="/">
<input type="text" id="3" name="3" class="today" value="/">
<p id="counter"></p>

The counter tag will display 3 after first key up. 首次按键后,计数器标签将显示3。 When i change the value in the text boxes the value does not change in the counter box. 当我更改文本框中的值时,计数器框中的值不会更改。 EG when i chance the value of text box 3 to x the EG当我有机会将文本框3的值改为x时

tag should now contain the number 2. Currently this does not change. 标签现在应该包含数字2.目前这不会改变。

You are using an attribute selector, but when you change the input value, it won't change the attribute; 您正在使用属性选择器,但是当您更改输入值时,它不会更改属性; just the property. 只是财产。 You can use filter() to get what you need: 您可以使用filter()来获得所需内容:

$('.today').keyup(function() {
    var Presents = $('input:visible').filter(function(){
      return this.value == "/";  
    });
    $("#counter").html( "Present: " + Presents.length );
});

JSFiddle 的jsfiddle

If you needed to update the attribute itself, you can do simply by adding the following to the top of your event handler: 如果您需要更新属性本身,只需将以下内容添加到事件处理程序的顶部即可:

$(this).attr('value',this.value);

JSFiddle 的jsfiddle

But that seems pretty messy to me. 但这对我来说似乎很混乱。 Also, I believe filter() will be faster than an attribute selector anyway. 另外,我相信filter()会比属性选择器更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM