简体   繁体   English

根据选项选择具有值的onchange调用方法

[英]Select onchange calls method with value depending on option

This following method is already called from multiple different places so I wouldn't like to change signature. 已经从多个不同的地方调用了以下方法,因此我不想更改签名。

doSomething(json){
  ...
}

Now I also need to call this method each time a new option is selected from a select field. 现在,每次从选择字段中选择一个新选项时,我还需要调用此方法。 Each option has some specific json to that option. 每个选项都有一些特定于该选项的json。 I need to achieve something like this: 我需要实现以下目标:

<select onchange="doSomething(json)">
  <option value="1" json="{'key': 'json1'}">name 1</option>
  <option value="2" json="{'key': 'json2'}">name 2</option>
</select>

How can I get the json attribute of selected option to the method? 如何获得方法的selected选项的json属性?

I would recommend you to use custom data-* attribute to persist arbitrary information which can be retrived later by using .data(key) 我建议您使用自定义data-*属性来保留任意信息,以后可以通过使用.data(key)进行检索。

As you don't want to modify the doSomething method, attach another click handler. 由于您不想修改doSomething方法,因此请附加另一个单击处理程序。 You can target the option using :selected selector 您可以使用:selected选择器来定位选项

 $('#yourSelect').on('change', function() { //Retrieve data var json = $(this).find(':selected').data('json'); //call the method doSomething(json); }).change(); function doSomething(json) { console.clear(); console.log(json); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="yourSelect"> <option value="1" data-json='{"key": "json1"}'>name 1</option> <option value="2" data-json='{"key": "json2"}'>name 2</option> </select> 

Any code run from the onchange="" handler has this set to the element it's an attribute of, namely the select element. onchange=""处理程序运行的任何代码都this设置为其属性的元素,即select元素。 Therefore the following code works: 因此,以下代码有效:

 <select onchange="alert(this.options[this.selectedIndex].getAttribute('json'))"> <option value="1" json="{'key': 'json1'}">name 1</option> <option value="2" json="{'key': 'json2'}">name 2</option> </select> 

As another poster said, it is recommended to prepend such attribute names with data- : 正如另一位发布者所说,建议在此类属性名称前添加data-

data-* - HTML | data- *-HTML | MDN MDN

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM