获取元素的值
Get element's value
我正在尝试检查一个元素的值,但它 returns undefined
虽然它在我检查其 class.
时有效
HTML:
<div class='cube' value='test' onclick='checkCube(this)'></div>
JavaScript:
function checkCube(cube) { // - there's either one of those lines, not both)
var check = cube.value; //This is not working,
var check = cube.className; //This is.
console.log(check);
}
value
属性 仅支持 输入元素
对非输入元素使用getAttribute
var check = cube.getAttribute("value");
您可以使用 getAttributes.getAttribute() 方法returns获取元素的具有指定名称的属性的值。
function checkCube(cube) {
var check = cube.value;
var check = cube.className;
console.log(cube.getAttribute("value"));
}
<div class='cube' value='test' onclick='checkCube(this)'>click Over Me</div>
进行如下操作。
function checkCube(cube) {
var check = cube.getAttribute("value");
alert(check);
}
<div class='cube' value='test' onclick="checkCube(this)">Click me to get Value</div>
当您将额外的属性(不是标签全局属性)附加到您的元素时,最好使用 data-* attributes
:
<div class='cube' data-value='test' onclick='checkCube(this)'></div>
然后使用dataset
来检索属性值,如:
var check = cube.dataset.value;
我正在尝试检查一个元素的值,但它 returns undefined
虽然它在我检查其 class.
HTML:
<div class='cube' value='test' onclick='checkCube(this)'></div>
JavaScript:
function checkCube(cube) { // - there's either one of those lines, not both)
var check = cube.value; //This is not working,
var check = cube.className; //This is.
console.log(check);
}
value
属性 仅支持 输入元素
对非输入元素使用getAttribute
var check = cube.getAttribute("value");
您可以使用 getAttributes.getAttribute() 方法returns获取元素的具有指定名称的属性的值。
function checkCube(cube) {
var check = cube.value;
var check = cube.className;
console.log(cube.getAttribute("value"));
}
<div class='cube' value='test' onclick='checkCube(this)'>click Over Me</div>
进行如下操作。
function checkCube(cube) {
var check = cube.getAttribute("value");
alert(check);
}
<div class='cube' value='test' onclick="checkCube(this)">Click me to get Value</div>
当您将额外的属性(不是标签全局属性)附加到您的元素时,最好使用 data-* attributes
:
<div class='cube' data-value='test' onclick='checkCube(this)'></div>
然后使用dataset
来检索属性值,如:
var check = cube.dataset.value;