如何提示更改h1框的文本

How to prompt to change text of an h1 box

本文关键字:h1 文本 何提示 提示      更新时间:2024-06-30

我想更改页面的标题,它位于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);