jQuery在表单中显示none选项



我想在表单中不显示任何选项

HTML:

<option class="level-0" value="top-10-villen-de">Top-10-Villen</option>
jQuery:

if(jQuery('option').attr('value') == 'top-10-villen-de'){
    jQuery(this).css('display', 'none');
}

我的if语句有问题,但是我不知道问题在哪里。

有人能帮帮我吗?

谢谢。

隐藏下拉选项不兼容所有浏览器

我有更好的选择。wrap将选项转换成span,当你需要它时,unwrap

提琴链接:http://jsfiddle.net/xms2uydx/

您使用了错误的this查看this Scope

http://jsfiddle.net/kevalbhatt18/r2m2ucgv/2/

上面的例子是给你两者之间的区别。1. 它来自于Jquery。2. 这是jquery函数的内部。

  1. 所以你可以在例子中看到第一个控制台i。e console.log(this)将返回窗口对象。

2。$(this)在click函数中会给你不同的值它与你的按钮相关它会给你按钮作用域

也可以用

jQuery("选项");(.level-0) . css("显示","没有一个")如果你知道option的类


<我>

<button>option 1</button>
<button>option 2</button>
<select>
    <option class="level-0" value="top-10-villen-de">Top-10-Villen</option>
    <option class="level-1" value="top-1">Top-20</option>
</select>

Jquery


<我>

console.log(this)
$('button').click(function () {
    if ($(this).text() === "option 1") {
        if (jQuery('option').attr('value') == 'top-10-villen-de') {
            console.log('inside')
            console.log(jQuery('option[class="level-0"]'))
            jQuery('option[class="level-0"]').css('display', 'none');
        }
    } else {
        jQuery('option[class="level-0"]').toggle()
    }
})

这是因为if语句中的上下文this没有引用选项元素。实现此目标的正确方法是找到属性值等于top-10-villen-de.hide()的元素:

jQuery('option[value="top-10-villen-de"]').hide();

仅供参考,隐藏选项元素不起作用。一个很好的解决方法是通过将disabled属性设置为true来禁用该选项。

在jQuery中,当你在DOM中有多个元素时,你必须使用$('selector').each(function(index,Obj){})来访问所有元素。

使用此代码隐藏所需的选项

$('#temp').find('option').each(function(index,Obj){
if($(this).attr('value')=='2')
$(this).css('display', 'none');
})

当值为top-10-villen-de时,可以设置为不显示

jQuery( "select" ).change(function() {
  if(jQuery(this).val() == 'top-10-villen-de'){
    jQuery(this).find("option[value='top-10-villen-de']").css('display', 'none');
  }
});

Here the fiddle

https://jsfiddle.net/jva8ju1s/

最新更新