如何使用一些元素值作为条件来隐藏一些带有jquery的元素?

时间:2014-02-20 14:58:55

标签: javascript jquery

我有以下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?

3 个答案:

答案 0 :(得分:1)

$("#hideToggle").click(function(){
    $("#item").find("input").each(function(){
        if(this.value <= 0) {
           $(this).parent().toggle();
        }
    });
});

$("#showAll").click(function(){
   $("#item").children("div").show();
});

JSFiddle

答案 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 
        }
    });
});

这是Demo

相关问题