简体   繁体   English

一个的多个值<option>

[英]Multiple values for one <option>

I'm trying to gain a better js-knowledge, and got a little problem. 我正在努力获得更好的js知识,并且遇到了一些问题。 I want to give a option more than one vaule, and from what i could find other places, arrays with split was the best solution. 我想给出一个多个选项的选项,从我能找到的其他地方,带分割的数组是最好的解决方案。 But I can't get it to work. 但我无法让它发挥作用。 One side of the script is supposed to calculate a price, dependent on the selected destionation, while the other is the name on the destinaton. 脚本的一面应该根据选定的destionation计算价格,而另一面是destinaton上的名称。

<form name="ORDER" method="post" >
<select name="destination" id="destination_trV">
<OPTION VALUE="10,Cannes"> Cannes</option>
</form>

I want one part to grab the "10" to use this calculation purposes, and another to grab "Cannes" to write. 我希望一部分抓住“10”来使用这个计算目的,另一部分抓住“戛纳”来写。

var dest_1 = (document.getElementById("destination_trV").value);
var vari_1 = dest_1.split(",",1);
var vari_2 = dest_1.split(",",1,2);

this is supposed to write out "10" 这应该写出“10”

document.getElementById("linje5").innerHTML="Priceclass: " + vari_1 + "<br>";

this is supposed to write out "Cannes" 这应该写出“戛纳”

document.getElementById("linje6").innerHTML="Destination: " + vari_2 + "<br>";

But this doesn't work :) 但这不起作用:)

Split does not work that way MDN split 拆分不能像MDN拆分那样工作

string.split([separator][, limit])

Just do the split once 只做一次拆分

var vals = dest_1.split(",");
var vari_1 = vals[0];
var vari_2 = vals[1];

A better way would be to use data attributes. 更好的方法是使用数据属性。

What would happen if one of those values were to contain a , character? 如果其中一个值包含一个字符,会发生什么? You'd need some form of encoding to preserve the original data. 您需要某种形式的编码来保留原始数据。 Instead of trying to jam multiple values into a single attribute, you'd be better off splitting those values into separate [data-*] attributes : 您最好将这些值拆分为单独的[data-*]属性 ,而不是尝试将多个值绑定到单个属性中

...
<option value="Cannes" data-destination="Cannes" data-price-class="10">Cannes</option>
...

That way, when you want the values, you can select the element and get the attribute values separately: 这样,当您需要值时,可以选择元素并单独获取属性值:

(function () {
    var opt,
        destination,
        priceClass;
    opt = document.getElementById("destination_trV");
    destination = opt.getAttribute('data-destination');
    priceClass = opt.getAttribute('data-price-class');
    document.getElementById('linje5').innerHTML = 'Priceclass: ' + priceClass + '<br>';
    document.getElementById('linje6').innerHTML = 'Destination: ' + destination + '<br>';
}());

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

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