来自输入属性jQuery的数组

时间:2014-12-11 12:14:53

标签: javascript jquery

如果每个输入都有inArray属性,则需要检查每个输入然后显示此输入,否则隐藏

我的HTML代码

<label class="priceswrapper" tour_type="reg, div">Price
<input  name="adult_cost"  type="text"/>
</lable>
<label class="priceswrapper" tour_type="reg, div">Price
<input  name="kids_cost"  type="text"/>
</lable>
<label class="priceswrapper" tour_type="div">Price
<input  name="intro_dive"  type="text"/>
</lable>
<label class="priceswrapper" tour_type="div">Price
<input  name="pro_dive"  type="text"/>
</lable>
<label class="priceswrapper" tour_type="qud">Price
<input  name="quad_price"  type="text"/>
</lable>

jQuery代码

jQuery(document).ready(function() {
  $('.priceswrapper').each(function(){
    var data = 'reg';
    var types = [$(this).attr('tour_type')];
    if ($.inArray(data, types) !== -1) {
        $(this).show();
            }else {
               $(this).hide();
               }
  });   
});

2 个答案:

答案 0 :(得分:1)

尝试这样:

<script>
jQuery(document).ready(function() {
      $('.priceswrapper').each(function(){
        var data = 'reg';
        var types = $(this).attr('tour_type').split(',');// you should get string fron here.
        console.log(types);
        if ($.inArray(data, types) !== -1) {
            $(this).show();
                }else {
                   $(this).hide();
                   }
      });   
    });


</script>
<label class="priceswrapper" tour_type="reg, div">Price
<input  name="adult_cost"  type="text"/>
</lable>
<label class="priceswrapper" tour_type="reg, div">Price
<input  name="kids_cost"  type="text"/>
</lable>
<label class="priceswrapper" tour_type="div">Price
<input  name="intro_dive"  type="text"/>
</lable>
<label class="priceswrapper" tour_type="div">Price
<input  name="pro_dive"  type="text"/>
</lable>
<label class="priceswrapper" tour_type="qud">Price
<input  name="quad_price"  type="text"/>
</lable>

答案 1 :(得分:0)

你可以用它。 FIDDLE

<强> HTML

<label class="priceswrapper" data-type="reg, div">Price
    <input  name="adult_cost"  type="text"/>
</label>
<label class="priceswrapper" data-type="reg, div">Price
    <input  name="kids_cost"  type="text"/>
</label>
<label class="priceswrapper" data-type="div">Price
    <input  name="intro_dive"  type="text"/>
</label>
<label class="priceswrapper" data-type="div">Price
    <input  name="pro_dive"  type="text"/>
</label>
<label class="priceswrapper" data-type="qud">Price
    <input  name="quad_price"  type="text"/>
</label>

<强>的jQuery

    var data = 'reg';
    $('.priceswrapper').each(function(idx, obj) {
        var types = $(this).data('type').split(/,\s+/);
        console.log(types);
        console.log($.inArray(data, types));
        if ($.inArray(data, types) !== -1) {
            $(obj).show();
        } else {
            $(obj).hide();
        }
    });