这是一个经典问题但无法找到最佳方法。我有一个选择类型的下拉菜单和3个值(早餐,糖果,咖啡店)。
如果选择了值=早餐,则显示div与类sf-field-post-meta-breakfast并且仅显示此类。必须隐藏div sf-field-post-meta-candy和sf-field-post-meta-coffeeshop。我还希望在加载视图时实现这一点,而不仅仅是在更改时。
<script>
jQuery(function($) {
$('.sf-field-post-meta-typeofmeal .sf-input-select').change(function () {
alert($(this).val);
if($(this).val()=="breakfast")
{
$('.sf-field-post-meta-breakfast').show();
}
else
{
$('.sf-field-post-meta-breakfast').hide();
}
});
})
</script>
问题是当值sf-field-post-meta-typeofmeal
改为发送给我时
function (a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}
答案 0 :(得分:0)
如果你的html是这样的(请注意,我添加了一个类'test-class'以使选择更容易):
<div class="sf-field-post-meta-typeofmeal">
<select class="sf-input-select">
<option value="breakfast">Breakfast</option>
<option value="candy">Candy </option>
<option value="coffeeshop">Coffeeshop</option>
</select>
</div>
<div class="sf-field-post-meta-breakfast test-class" hidden>Breakfast description</div>
<div class="sf-field-post-meta-candy test-class" hidden>Candy description</div>
<div class="sf-field-post-meta-coffeeshop test-class" hidden>Coffeeshop description</div>
将脚本调整为此,它应该可以工作: -
$(function () {
$('.sf-field-post-meta-typeofmeal .sf-input-select').change(function () {
// Hide all the divs using the 'test-class' selector
$.each($('.test-class'), function () {
$(this).hide();
});
// Check the value selected and show the associated div
switch ($(this).val()) {
case 'breakfast':
$('.sf-field-post-meta-breakfast').show();
break;
case 'candy':
$('.sf-field-post-meta-candy').show();
break;
case 'coffeeshop':
$('.sf-field-post-meta-coffeeshop').show();
break;
}
});
// Trigger 'change' when the html document has loaded to set the div visibility
$('.sf-field-post-meta-typeofmeal .sf-input-select').trigger('change');
});
您获得价值的原因是因为alert($(this).val);
应为alert($(this).val());
希望它有所帮助。