[英]Get element's value
我正在嘗試檢查元素的值,但它返回undefined
雖然它在我檢查它的類時有效。
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");
將額外屬性(不是標記全局屬性)附加到元素時,最好使用data-* attributes
:
<div class='cube' data-value='test' onclick='checkCube(this)'></div>
然后使用dataset
檢索屬性值,如:
var check = cube.dataset.value;
您可以使用getAttributes獲取.getAttribute()方法返回具有指定名稱的屬性的值。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.