我有以下html:
<button id="hideToggle">show/hide</button>
<form id="item">
<div>Item 1 <input name="item1" type="number"/></div>
<div>Item 2 <input name="item2" type="number"/></div>
<div>Item 3 <input name="item3" type="number"/></div>
</form>
我如何隐藏<div>
内的<form>
,条件是,当点击<button>
时,如果<input>
值大于0,则不会隐藏,否则会隐藏<div>
?
如何编写此需要的javascript和/或jquery?
答案 0 :(得分:1)
$("#hideToggle").click(function(){
$("#item").find("input").each(function(){
if(this.value <= 0) {
$(this).parent().toggle();
}
});
});
$("#showAll").click(function(){
$("#item").children("div").show();
});
答案 1 :(得分:0)
试试这个:
$(document).on("click","#hideToggle",function(){
$("#item input").each(function(){
if(!(parseInt($(this).val()) > 0)){
$(this).parent().hide();
}
});
});
答案 2 :(得分:0)
以下是检查值是否为Number
的代码。所有描述都在评论中:
//attach click listener to the button
$(document).on("click", "#hideToggle", function(){
//get all input type="number", descendant to "#item"
var inputs = $("#item").find("input[type='number']");
//go over each input
$.each(inputs, function(index, elem){
//try to parse it's value as a number
var number = parseInt($(elem).val());
//if value is a number
if(!isNaN(number)){
var hideCondition = number <= 0;
if(hideCondition) {
//hide the parent div
$(elem).parent("div").hide();
}
} else {
//do something if value is not a number
}
});
});