[英]How to prompt to change text of an h1 box
我想在h1框中更改页面标题。 我知道我必须使用onclick函数,但是我只使用过带有按钮的此函数。 鼠标单击h1框时如何更改页面标题?
这是我的JS HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practice</title>
<link rel='stylesheet' href='main.css'/>
</head>
<script>
function changeTitle() {
var title = prompt("Change the title:");
}
</script>
<body>
<div>
<h1 onclick="changeTitle()">To-Do List</h1>
<ul class='todo-list'>
<li class='todo-item'>4L 2% Milk
<span class='remove'></span></li>
<li class='todo-item'>Butter, Unsalted
<span class='remove'></span></li>
<li class='todo-item'>Dozen Eggs
<span class='remove'></span></li>
<li class='todo-item'>Walk the dog
<span class='remove'></span></li>
<li class='todo-item'>Cut the lawn
<span class='remove'></span></li>
<li class='todo-item'>Laundry
<span class='remove'></span></li>
<li class='todo-new'>
<input id='new-item-text' type='text'/>
<a id='add-item' href='#'>+</a>
</li>
</ul>
</div>
<script src='main.js'></script>
</body>
</html>
您接近了,您只需要将innerText
设置为从prompt()
返回的标题。 访问h1
的最简单方法是将其传递到changeTitle()
。 单击它时,它可以作为this
,然后我们可以在函数中使用它。
function changeTitle(element) { var title = prompt("Pick a new title:"); element.innerText = title; }
<h1 onclick="changeTitle(this)">First Title</h1>
你可以试试这个
<h1 id="myTitle">To-Do List</h1>
然后..
function changeTitle() {
var title = prompt("Change the title:");
if(title){
this.innerText = title
}
}
var el = document.getElementById("myTitle");
el.addEventListener("click", changeTitle);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.