我是编码的新手,需要在页面上以HTML形式创建HTML文本,并在Javascript警报框中打开该文本。我尝试过各种代码,但均未成功。到目前为止,这是我所提出的,不会创建弹出警报框:
这里是HTML和JS:
<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>
```
Function myfunction1()
{
Let myfun1 = document.getElementById('sec1-input').value;
Alert(myfun1);
}
我不确定您想要什么,但是我将向您展示如何完全按照您的要求创建警报窗口。首先,您必须考虑自己犯的几个错误。 JavaScript无法识别单词Function,因为它是大写的。 function关键字必须为小写。
在这里,我为您提供带有JavaScript保留字的引荐链接:https://www.w3schools.com/js/js_reserved.asp
另一方面,我看到您没有使用form标记,这导致了两个问题:技术和语义。在这里,我为您提供了另一个引用表单的链接:https://www.w3schools.com/html/html_forms.asp
最后,要实现所需的功能,您需要使用事件,尤其是单击事件。在这里,我将给您留下reference link和您想要的解决方案:
let button = document.querySelector('#sec1-btn1');
button.addEventListener('click', function(e) {
let val = document.querySelector('#sec1-input').value;
alert(val);
});
<form>
<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>
</form>
您尚未在任何地方调用该函数。为了使其正常工作,您需要使用侦听器。
<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 onclick="myfunction1()" id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>
<script>
function myfunction1() {
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1)
}
</script>
我将onClick
侦听器添加到button
,现在可以使用。
javaScript区分大小写
function myfunction1()
{
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1);
}
<div class="form-group">
<label for="sec1-label"><strong>Enter Alert Text: </strong></label>
<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>
元素的ID也不应相同,要分配相同的选择器,请使用类,并且还需要将函数提供给元素的事件侦听器
<button id="sec1-btn1" type="button" class="btn btn-primary" onclick="myfunction1()">Alert Me!</button>