我已经谷歌搜索,所以请不要告诉我谷歌搜索,因为我不明白自己做错了什么。当我按下 Submit (提交)按钮时,网站上没有任何反应。
这是我的 HTML 文件:
<button onclick="runThis()">Submit</button>
<h1 id="apples">Hello</h1>
<script>
function runThis() {
var getTextID = document.getElementsByTagName("apples");
getTextID = "Hello guys";
}
</script>
mac user,如果有什么不同的话。
答案 0 :(得分:2)
首先, 苹果 不是标签名称,它是元素的 id 。标签名称为 h1 。
然后getElementsByTagName()
返回选择。您必须使用特定的 index :
getElementsByTagName('h1')[0]
尽管您尝试获取具有 id 属性的元素应该是getElementsById()
。此外, getTextID 指的是元素本身,您必须使用 textContent 或 innerText 属性来设置元素中的文本。
尝试以下方式:
function runThis(){
var getTextID = document.getElementById("apples");
getTextID.textContent = "Hello guys";
}
<button onclick="runThis()">Submit</button>
<h1 id="apples">Hello</h1>
答案 1 :(得分:0)
尝试使用它;
document.getElementById("apples")
答案 2 :(得分:0)
您使用了错误的选择器。
getElementsByTagName()
将查找元素标签名称 h1 而不是 ID 。
将查询选择器替换为document.getElementById("apples")
,并设置新内容,您可以使用getTextID.textContent = "Hello guys";
function runThis() {
var getTextID = document.getElementById("apples");
getTextID.textContent = "Hello guys";
}
<button onclick="runThis()">Submit</button>
<h1 id="apples">Hello</h1>
如果您有任何疑问,请在下面发表评论,我们会尽快与您联系。
我希望这会有所帮助。编码愉快!
答案 3 :(得分:0)
您也可以使用querySelector
和innerHTML
。
function runThis() {
var getTextID = document.querySelector("#apples");
getTextID.innerHTML = "Hello guys";
}
<button onclick="runThis()">Submit</button>
<h1 id="apples">Hello</h1>
请在此处查看有关getElement *和querySelector *的更多信息:https://javascript.info/searching-elements-dom
答案 4 :(得分:0)
您正在使用的方法getElementsByTagName返回具有标签名称的元素,而不是具有所需ID的单个元素。要解决此问题,请添加,而改用getElementById:
var getTextID = document.getElementById("apples");
第二,您需要替换元素的内部文本,而不是元素本身,因此您应该使用innerText:
getTextID.innerText = "Hello guys";
完整的演示:
function runThis() {
var getTextID = document.getElementById("apples");
getTextID.innerText = "Hello guys";
}
<button onclick="runThis()">Submit</button>
<h1 id="apples">Hello</h1>
希望这会有所帮助!
答案 5 :(得分:-2)
function runThis(){
document.getElementById("apples").innerHTML = "Problem solved ";
}