javascript 使用 jQuery filter() 获取所有匹配的 .val()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9075050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jQuery filter() to get all matched .val()
提问by Nyxynyx
I have a number of textfields and I need to select the values of those textfields whose values are not equal to their title
attribute.
我有许多文本字段,我需要选择那些值不等于它们的title
属性的文本字段的值。
Problem:With my attempt, the jQuery code below simply selects the value of the first matched textfield. How do I get all matched textfields' values?
问题:通过我的尝试,下面的 jQuery 代码只是选择了第一个匹配文本字段的值。如何获取所有匹配的文本字段的值?
jQuery Code
jQuery 代码
var inputs = $(".input").filter(function() {
return $(this).val() != $(this).attr('title');
}).val();
console.log(inputs);
回答by Nurlan
Here is simpler solution:
这是更简单的解决方案:
var input = [];
jQuery('input[type=text]').each(function(){
if(jQuery(this).val() != jQuery(this).attr('title') ) {
input.push(jQuery(this).val());
}
});
回答by Kevin B
The .val()
method only returns the value of the first element in the selected list of elements. Try turning it into an array instead:
该.val()
方法仅返回所选元素列表中第一个元素的值。尝试将其转换为数组:
var inputs = $(".input").filter(function() {
return $(this).val() != $(this).attr('title');
}).map(function(){
return $(this).val();
}).get();
console.log(inputs);
回答by grc
Here's one way to do it:
这是一种方法:
var inputs = [];
$(".input").filter(function() {
return $(this).val() != $(this).attr('title');
}).each(function() {
inputs.push($(this).val());
});
console.log(inputs);
Example: http://jsfiddle.net/grc4/cCRfE/