问题
This is totally mysterious. I checked everything, googled everything, but looks like this should work. I've done same things in my code with others html elements and they all give me the values, but this time I'm getting undefined for this particular HTML element. The snippet of code below:
<div class="pianoKeyboard">
<button id="octaveUp" value="off">Octave Up</button>
<button id="octaveDown" value="off">Octave Down</button>
<div id="octaveNum" value='0'>Default</div>
var octaveNumber = document.getElementById("octaveNum");
octaveup.addEventListener("click", function(e) {
if (booleanVal == false) {
booleanVal = true;
console.log(octaveNumber.value);
Do you see any problem? Because I don't. I can console.log
the element itself without the value, but if I add .value
to it, I get undefined
.
回答1:
That is because <div>
elements do not have a value
attribute. It is only for a selected subset of elements: <button>
, <option>
, <input>
, <li>
, <meter>
, <progress>
, and <param>
.
You can store the value as a HTML5 data- attribute, i.e.:
<div id="octaveNum" data-value='0'>Default</div>
The value of the data-
attribute can simply be accessed programmatically using:
document.getElementById('octaveNum').dataset.value
The data-
attribute offers you tremendous flexibility over the naming of variables: it doesn't even have to be data-value
. For example, if you want to store the default and current octaves, you can choose to store it as data-default-octave
and data-current-octave
, and access it as selector.dataset.defaultOctave
and selector.dataset.currentOctave
respectively (note the conversion of dash-delimited attribute name in HTML5 to camelCase keys in JS).
Data attribute names which contain hyphens will be stripped of their hyphens and converted to CamelCase.
See proof-of-concept below:
var octaveNumber = document.getElementById("octaveNum");
var octaveUp = document.getElementById("octaveUp");
octaveUp.addEventListener("click", function(e) {
console.log(octaveNumber.dataset.value);
});
<div class="pianoKeyboard">
<button id="octaveUp" value="off">Octave Up</button>
<button id="octaveDown" value="off">Octave Down</button>
<div id="octaveNum" data-value='0'>Default</div>
</div>
回答2:
div
element have no value
attribute, so you can't use octaveNumber.value
to get it
来源:https://stackoverflow.com/questions/45664269/html-elements-value-property-is-giving-undefined-value