[英]Javascript adding fields dynamically (onClick)
我正在嘗試動態添加一些字段。 例如,當用戶單擊復選框或單選按鈕時,會出現一些額外的字段(按鈕、文本字段等)。 如果是的話,我可以用 onClick 來做到這一點,我該怎么做?
謝謝!
網站中已有按鈕,只需使用以下某種形式隱藏它們:
<button style="display: none"></button>
然后,您可以根據需要顯示和隱藏它們。
<html>
<head>
<title>My Page</title>
<style>
#button2 {
display: none;
}
</style>
</head>
<body>
<button onclick="show('button2')">Click Me!</button>
<button id="button2">Click Me!</button>
<script>
function show(element) {
document.getElementById(element).style.display = block;
}
</script>
</body>
</html>
最簡單的方法,
讓您想要在 html 中預編碼但使用 css 隱藏的元素出現。
例如:
// If enyone "change" the magic checkbox, ... I will know it document.getElementById('magic_checkbox').addEventListener('change', function(){ // Is it checked... because if it is, // I should show the more inputs if(this.checked){ document.getElementById('some_more_data').style.display = "block"; } // If it is unchecked // I should hide them else{ document.getElementById('some_more_data').style.display = "none"; } }, false);
<!-- The mahic check box --> <input id="magic_checkbox" type="checkbox" name="something" value="a_value"> Do you want more?<br> <!-- My hidden inputs --> <div id="some_more_data" style="display:none;"> <input type="text" name="other_data_no1" value="Yeah!"><br> <input type="text" name="other_data_no2" value="Fill me!"> </div> <!-- Some other data --> <input type="number" name="something_else" value="123"><br>
你可以。 此代碼復制形式: http : //www.w3schools.com/jsref/met_document_createelement.asp
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode("CLICK ME"); // Create a text node
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn); // Append <button> to <body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.