dil*_*ilm 23 javascript jquery jquery-selectors
我想问一下jQuery中是否有更好的方法来选择多个文本输入然后检查它们中是否有值.这是我的代码:
if ($("#reference").val() != "" || $("#pin").val() != "" || $("#fName").val() != "" || $("#mName").val() != "" || $("#datepicker").val() != "") { /*logic goes here */ }
Run Code Online (Sandbox Code Playgroud)
xda*_*azz 52
你可以这样做:
if ($("#reference,#pin,#fName,#mName,#datepicker").filter(function() { return $(this).val(); }).length > 0) {
//..
}
Run Code Online (Sandbox Code Playgroud)
使用如下的常用功能可以使其重用:
function hasValue(elem) {
return $(elem).filter(function() { return $(this).val(); }).length > 0;
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样称呼它:
hasValue("#my-input-id");
Run Code Online (Sandbox Code Playgroud)
Shi*_*jin 10
尝试jQuery each()
$('input[type=text]').each(function(){
var text_value=$(this).val();
if(text_value!='')
{
console.log('Value exist');
}
})
Run Code Online (Sandbox Code Playgroud)
获取length
属性的问题filter()
在于 jQuery 将评估集合中的每个元素,只是为了在我们关心的只是值是否大于零时填充计数。
当前的答案,甚至 jQuery 自己的.is()
, .has()
, 和.filter()
一旦满足条件就使用短路。
您可以定义一个简单的扩展方法,.any()
如下所示:
jQuery.fn.any = function(filter){
for (i=0 ; i<this.length ; i++) {
if (filter.call(this[i])) return true;
}
return false;
};
Run Code Online (Sandbox Code Playgroud)
然后传入这样的过滤函数:
var someInputsEmpty = $("#reference,#pin,#fName,#mName,#datepicker").any(function() {
return this.value == '';
});
Run Code Online (Sandbox Code Playgroud)
jQuery.fn.any = function(filter){
for (i=0 ; i<this.length ; i++) {
if (filter.call(this[i])) return true;
}
return false;
};
$(function() {
var gotMatch = $(":input").any(function() {
return this.value == 'hi';
});
if (gotMatch) {
console.log("Hello to you too!");
} else {
console.log("Why don't you say Hi!");
}
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
65538 次 |
最近记录: |