选择选项时,JQuery Hide Div [英] JQuery Hide Div when Option is Selected

查看:105
本文介绍了选择选项时,JQuery Hide Div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当选择特定的OPTION值时,我要隐藏一个DIV类

I want to hide a class of a DIV when a specific OPTION Value is selected

    <select id="tagtype" name="type">
        <option value="type_s">Standard</option>
        <option value="type_o">Overstock</option>
        <option value="type_snd">Scratch &amp; Dent</option>
        <option value="type_mult">Multiples</option>
    </select>

<div class="multiples>stuff here</div>

<script type="text/javascript"> 
$(document).ready(function() {
  if ($("#tagtype option[value='type_mult']").length)
   $("multiples").css('display','none');

});
</script>


推荐答案

更好的方法可能是这样的:

A better way to do this would probably be something like the following:

jQuery(document).ready(function() {
   jQuery("#tagtype").change(function() {
      if(jQuery(this).find("option:selected").val() == "type_mult") {
         jQuery(".multiples").hide();
      }
   });
});

您正在将处理程序绑定到选择框的 onChange 事件。

You're binding a handler to the onChange event of the select box. Whenever, you select a new option in the select box, the handler is called.

在处理程序中, this 引用激活 onChange 事件的选择框,查找所选选项的值。如果此值等于type_mult,则使用类 multipples 隐藏所有元素。

In the handler, this refers to the select box that fired the onChange event. You look for the value of the selected option. If this value is equal to "type_mult", you hide all elements with the class multiples.

你现有的代码是它只会运行一次;当页面首次完成加载时。您需要响应选择框中的更改,这就是为什么您需要绑定到 onChange 事件。另一个问题是 if 语句。即使你使用你的代码和在 onChange 处理程序,它输入 if 阻止每种类型,因为你不检查以查看是否选择了具有type_mult值的选项。你只是检查看看是否存在。由于总是存在, if 中的代码将始终运行。另外,当你想使用类名时,你需要在类名前放一个句点。所以你想做 $(。multipleples)而不只是 $(multiples)标签多个,这不是你想要的)。

The problem with your existing code is that it will only run once; when the page first finishes loading. You need to respond to changes in the select box, which is why you need to bind to the onChange event. Another problem is the if statement. Even if you used your code and in an onChange handler, it enter the if block every type because you are not checking to see if the option with the "type_mult" value is selected. You're simply checking to see if it exists. Since it always exists, the code inside the if will always run. Also, when you want to use class names, you need to put a period in front of the class name. So you want to do $(.multiples) and not just $(multiples) (the latter will search for a tag named multiples, which is not what you want).

这篇关于选择选项时,JQuery Hide Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆