如何提示更改h1框的文本

时间:2016-04-15 03:23:52

标签: javascript

我想更改页面的标题,这是在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>

2 个答案:

答案 0 :(得分:2)

您已关闭,只需将innerText设置为您从prompt()返回的标题即可。访问h1的最简单方法是将其传递到changeTitle()。点击后,它会显示为this,我们可以在功能中使用它。

&#13;
&#13;
function changeTitle(element) {
  var title = prompt("Pick a new title:");
  element.innerText = title;
}
&#13;
<h1 onclick="changeTitle(this)">First Title</h1>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以试试这个

<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);