[英]embedding multiple values in options of <select>
I need to embedd 2 values in each of the options of a drop down list and then need to be able to pass both of them to a JavaScript function. 我需要在下拉列表的每个选项中嵌入2个值,然后需要能够将它们都传递给JavaScript函数。
<select onChange="display(<?=$manufacturers_id?>,<?=$modelID?>,this.value1,this.value2);">
..
..
echo "<option value1=\"".$variantID."\" value2=\"".$month_year."\">".$products_variant." ".$month_year."</option>";
..
..
</select>
As you can see this HTML code is generated by PHP, I need these two values fetched from database to passed to a JS function. 正如您所看到的,这个HTML代码是由PHP生成的,我需要从数据库中获取这两个值以传递给JS函数。
I am open to suggestions on better way of doing this? 我愿意接受有关更好的方法的建议吗?
you cannot add many values in an option. 您无法在选项中添加许多值。 instead you can use datasets (html5), like:
相反,你可以使用数据集 (html5),如:
<select id="myselect">
<option data-this="foo" data-that="bar">
</select>
the javascript to read these values is: 读取这些值的javascript是:
var d = document.getElementById("myselect");
var _this = d.options[d.selectedIndex].dataset["this"];
var _that = d.options[d.selectedIndex].dataset["that"];
if you dont want to mess with datasets, you can store a JSON object: 如果你不想搞乱数据集,你可以存储一个JSON对象:
...
<option value='<?php echo json_encode(array("foo"=>1,"bar"=>2)); ?>'>
...
and extract the data like: 并提取如下数据:
var d = document.getElementById("myselect");
var option_value = JSON.parse( d.options[d.selectedIndex].value );
you choose 你选
EDITED: 编辑:
change this: 改变这个:
<select onChange="display(<?=$manufacturers_id?>,<?=$modelID?>,this);">
function display(manufacturers_id,modelid,obj) {
... json way
var option_value = JSON.parse(obj.options[obj.selectedIndex].value);
// option_value.foo = 1;
... dataset way
var _this = obj.options[obj.selectedIndex].dataset["this"];
// _this will have the "foo" value
}
I would render the options like this: 我会渲染这样的选项:
<option data-value1="X" data-value2="Y">
Then deal with these data- attributes however you want (with jQuery's data("value1")
method, with the native getAttribute("data-value1")
, etc. 然后使用jQuery的
data("value1")
方法,使用本机getAttribute("data-value1")
等处理这些数据属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.