首页 > 解决方案 > 单击按钮后,消息出现在同一个 div 中

问题描述

这是我的表格:

<div class="notification">
            <p style="font-family: 'Roboto', sans-serif;">Enter your email to notify you when the app you selected become available.</p>
                <form class="form-inline">
                    <div class="form-group">
                        <label for="inputemail"></label>
                        <input type="email" class="form-control" id="inputemail" placeholder="Email Address" size="25">
                    <button type="submit" class="btn btn-primary" onclick="displayMessage()">NOTIFY ME</button>
                    <small id="emailHelp" class="form-text text-muted">*we will never sell<br>your email</small>
                </div>
            </form>
        </div>

当我单击通知我按钮时,我希望我的表单消失,并且我想在该通知 div 中放置一条消息,如下所示:单击后 的消息最好的方法是什么?

标签: javascripthtmlcssformsbutton

解决方案


您需要了解,当您单击按钮时,浏览器会刷新页面,因此您需要添加监听并防止默认。从那里我简单地通过 Id 获取 div 元素并更改 innnerHTML 属性。

<script>

let string = 'We will email you when your app becomes available'

function handleClick(event){
  event.preventDefault();
  let notifDiv = document.getElementById("notifications");
  notifDiv.innerHTML = string
}

document.getElementById("notifications").addEventListener("click", handleClick)

</script>

推荐阅读