为什么在动态更改的情况下按“值"进行的Jquery选择器不起作用
问题描述:
我不确定为什么jquery选择器value
不起作用,尝试将输入的值更改为"a"
但length
不能递增,请检查下面的简单示例:
I'm not sure why jquery selector value
not work, Trying to change the value of inputs to "a"
but the length
not increment, please check the simple example bellow:
$('body').on('input', '.example', function() {
$('#result').text($('.example[value="a"]').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="example" value="a">
<input type="text" class="example" value="b">
<input type="text" class="example" value="c">
<div id='result'></div>
答
如果动态更改值,则属性选择器不会选择它.您可以改用filter()
.
If you are changing value dynamically it wouldn't get selected by attribute selector. You can use filter()
instead.
属性选择器不会检查dom节点的 value属性,它仅针对元素的属性
$('body').on('input', '.example', function() {
$('#result').text($('.example').filter(function() {
return this.value == 'a'
}).length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="example" value="a">
<input type="text" class="example" value="b">
<input type="text" class="example" value="c">
<div id='result'></div>
或者您需要在输入事件时手动更新element属性
Or you need to manually update the element attribute on input event
$('body').on('input', '.example', function() {
$(this).attr('value', this.value);
$('#result').text($('.example[value="a"]').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="example" value="a">
<input type="text" class="example" value="b">
<input type="text" class="example" value="c">
<div id='result'></div>