HTML Dropdown selection value

2019-07-31 09:26发布

问题:

I have the following code:

<select>
<option value="blablabla">Test</option>
<!-- ... -->
</select>

But I want to know if I can set the "value" attribute of the option tag, as a reference to an object (in javascript).

回答1:

The option value must be a "string" (that string can be a number).

What you want to do is a bit unusual but can be done (but I think there are better ways to achieve what you want to do)... You could serialize your object and set it in the value but that would be odd.

You could also index these references in an array and then set it's index in the value of the option...



回答2:

The "value" attribute could be a number that you can use later in javascript to reference a object in an array.



回答3:

As is so often the case, the answer is MAYBE.

The only way I can think of to do this off the top of my head, would be to have an array of objects, and have the indexes of the array to be the values found in the drop down list.

Of course, depending on the context of what you're trying to do, that may or may not be useful. For example, say you want a DIV to appear/disappear based on the selection. In that case, you wouldn't need the array, as you could just put the control's name into the VALUE field and perform a look up on it.



回答4:

Your question is a bit unclear. You can set the value of an item according to the value of the selected option:

<select id="mySelect">
  <option value="goose">Goose</option>
  <option value="gander">Gander</option>
</select>

var myObj = {a:"",b:true};
document.getElementById("mySelect").onchange = function() {
  myObj.a = this.value;
  alert(myObj.a);
}