在 HTML 表单中创建 HTML 文本并在 Javascript 警报框中打开文本

我是编码新手,需要在页面上的 HTML 表单中创建 HTML 文本,并在 Javascript 警报框中打开文本。我尝试了各种代码都没有成功。到目前为止,这是我想出的,它不会创建弹出警报框:


这是HTML和JS:


Function myfunction1()

{

  Let myfun1 = document.getElementById('sec1-input').value;

  Alert(myfun1);

}

<div class="form-group">

    <label for="sec1-input"><strong>Enter Alert Text: </strong></label>

    <input type="text" class="form-control" id="sec1-input">

</div>

<button id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button> 


ibeautiful
浏览 141回答 3
3回答

天涯尽头无女友

我不确定你想要什么,但我会告诉你如何完全按照你的要求制作一个警报窗口。首先,您必须考虑您正在犯的几个错误。JavaScript 无法识别 Function 这个词,因为它是大写的。function 关键字必须是小写的。在这里我给你留下一个带有 JavaScript 保留字的引用链接:https ://www.w3schools.com/js/js_reserved.asp另一方面,我看到您没有使用表单标签,这会导致两个问题:技术和语义。在这里,我给您留下另一个参考表格的链接:https ://www.w3schools.com/html/html_forms.asp最后,为了实现你想要的,你需要使用事件,尤其是点击事件。在这里我会给你一个参考链接和你想要的解决方案:let button = document.querySelector('#sec1-btn1');&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; button.addEventListener('click', function(e) {&nbsp; &nbsp; &nbsp; &nbsp; let val = document.querySelector('#sec1-input').value;&nbsp; &nbsp; &nbsp; &nbsp; alert(val);&nbsp; &nbsp; });&nbsp; &nbsp; <form>&nbsp; &nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <label for="sec1-input"><strong>Enter Alert Text: </strong></label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" class="form-control" id="sec1-input" />&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; <button id="sec1-btn1" type="button" class="btn btn-primary">&nbsp; &nbsp; &nbsp; &nbsp; Alert Me!&nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; </form>

莫回无

javaScript 区分大小写function myfunction1(){&nbsp; let myfun1 = document.getElementById('sec1-input').value;&nbsp; alert(myfun1);}<div class="form-group">&nbsp; &nbsp; <label for="sec1-label"><strong>Enter Alert Text: </strong></label>&nbsp; &nbsp; <input type="text" class="form-control" id="sec1-input"></div><button id="sec1-btn1" type="button" onClick="myfunction1()" class="btn btn-primary">Alert Me!</button>&nbsp;元素的 ID 也不应该相同,要分配相同的选择器,使用类,您还需要将函数提供给元素的事件侦听器

慕尼黑5688855

您还没有在任何地方调用该函数。为了让它工作,你需要使用一个监听器。<div class="form-group">&nbsp; &nbsp; <label for="sec1-input"><strong>Enter Alert Text: </strong></label>&nbsp; &nbsp; <input type="text" class="form-control" id="sec1-input"></div><button onclick="myfunction1()" id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>&nbsp;<script>function myfunction1() {&nbsp; let myfun1 = document.getElementById('sec1-input').value;&nbsp; alert(myfun1)}</script>我添加了onClick监听器button,现在它可以工作了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript