简体   繁体   English

如何编写jQuery / javascript if语句,以便在html时触发 <option>选择特定班级?

[英]how do I write a jQuery/javascript if statement so that it's triggered when a html <option> with a specific class is selected?

<select>
  <option value='34'>Trees</option>
  <option value='13' class='create_sub_category'>Add new sub-category</option>
  <option value='24' class='create_sub_category'>Add new sub-category</option>
  <option value='57'>Cats</option>
  <option value='34' class='create_sub_category'>Add new sub-category</option>
</select>



<script type='text/javascript'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
if (selected(".create_sub_category")) {
  alert('hi');
}
</script>

Obviously, there's no such javascript or jQuery function called 'selected' that I used above in my if statement, but could someone help me find something that would do what I'm describing? 显然,我在if语句中没有上面使用过的名为“ selected”的javascript或jQuery函数,但是有人可以帮助我找到可以做我所描述的东西吗?

$('select').change(function() {
  if($('select option:selected').hasClass('create_sub_category')) 
  {
    alert("SELECTED");
  }  
});

You should put some id/class on that select element. 您应该在该select元素上放置一些id / class。

You can do this: 你可以这样做:

if($("select option:selected").hasClass("create_sub_category")) {
  alert("hi");
}

The key here is: option:selected 这里的关键是:选项:已选择

No need for jQuery 不需要jQuery

if(/\bcreate_sub_category\b/.test(select.options[ select.selectedIndex ].className))
    //...

jsFiddle jsFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用javascript时,如何为所选选项创建if语句 - when using javascript how would i create an if statement for a selected option 如何使用 jQuery、JavaScript 和 HTML 动态设置下拉列表的选定选项? - How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML? 如何使用 JavaScript 更改 HTML 选定选项? - How do I change an HTML selected option using JavaScript? 如何在ap类中检查特定内容并在html文件中使用javascript创建if语句? - How do I check for specific content in a p class and create an if statement based on that with javascript in an html file? 使用JavaScript,我如何重置表单中的所有选择,以便选择每个选项的第一个选项? - Using JavaScript, how can I reset all the select's in my form so that the first option for each is selected? 使用Ajax HTML结构选择特定选项时的jQuery事件 - jQuery event when specific option is selected with Ajax HTML structure 在Javascript中如何将新选项添加​​到HTML选择中,以便根据文本的字母值插入 - In Javascript how do I add a new option into Html Select so inserted based on alphabetical value of text JavaScript和HTML-如何将组合框的选定选项的值放入跨度? - JavaScript and HTML - How do I put the value of a selected option of a combobox into a span? 当“不相关”的html select元素未选择任何选项时,如何退出jQuery事件? - How can I exit from a jQuery event when an “unrelated” html select element has had no option selected? 当 html 的 class 名称更改时,如何使用 JavaScript 执行某些操作? - How to do something with JavaScript when html's class name changes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM