[英]How to hide the DOM element with ngShow/ngHide when condition is not met?
[英]Javascript: Hide element if condition is met
我試圖根據其ID隱藏元素,但是,我無法讓它工作。 我用Google搜索了答案,但無論我做什么,我似乎無法讓它為我工作。
我的代碼附在下面。
<!DOCTYPE html>
<html>
<!-- HTML -->
<body>
<div id="role" value="Edit">
<button> Edit </button>
</div>
</body>
<!-- Javascript -->
<script>
if(document.getElementById("role").value == 'Edit'){
document.getElementById("role").style.display = 'none';
}
</script>
</html>
您可以使用下面的代碼,您想獲得屬性而不是值。
如果需要,可以使用querySelector而不是getElementById。
var role = document.querySelector('#role'); if(role.getAttribute('value') == 'Edit'){ role.style.display = 'none'; }
<!DOCTYPE html> <html> <!-- HTML --> <body> <div id="role" value="Edit"> <button> Edit </button> </div> </body> </html>
你試過這個嗎?
<!DOCTYPE html>
<html>
<!-- HTML -->
<body>
<div id="role" value="Edit">
<button> Edit </button>
</div>
</body>
<!-- Javascript -->
<script>
if(document.getElementById("role").getAttribute('value') == 'Edit'){
document.getElementById("role").style.display = 'none';
}
</script>
在您的示例document.getElementById("role").value
中.value是未定義的。 要檢索屬性值,您應該使用element.getAttribute('attr')
方法或element.attributes[attr].value
。
在你的情況下,它將是document.getElementById("role").attributes['value'].value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.