当单击按钮时,JavaScript函数将函数名称显示为undefined

时间:2018-01-12 11:26:08

标签: javascript jquery html

我正在测试如何使用Javascript更改文本和CSS元素

我的HTML中有三个按钮,到目前为止我只使用了一个按钮(更改标题)。我想点击按钮时更改H1文本。

使用我当前的编码,当我单击按钮时没有任何反应,我在Web开发人员工具控制台中显示以下内容:

* ReferenceError:未定义changeTitle [了解更多] Index.html:1:1

Onclick file:/// D:/Google%20Drive/Programming/EDX/Introduction%20to%20JavaScript/Module_1/index.html:1:1 *

问题:

  1. 有人可以帮助我理解为什么当我相信我已经在外部JS文件中定义了changeTitle函数时,浏览器说没有定义changeTitle函数。
  2. 我可以使用onclick方法吗?在标签元素中,以便我不必使用按钮?
  3. 请在下面找到摘录:

    
    
    $(document).ready(function() {
      function changeTitle() {
        var title = document.querySelector(".head-title");
        title.innerHTML += "<br>(or how to speak like a pirate)";
      };
    });
    &#13;
    * {
      margin: 0;
      padding: 0;
    }
    
    body {
      font-family: 'arial', sans-serif;
      max-width: 1000px;
      margin: 0 auto;
      padding-top: 50px;
    }
    
    header > h1 {
      background-color: #FEF1E0;
      color: #A47F1A;
      text-align: center;
      line-height: 100px;
      border: dashed 5px #A47F1A;
      border-radius: 40px;
      text-shadow: 2px 2px #3B2E2A
    }
    
     .nav {
      list-style-type: none;
      background-color: #3B2E2A;
      margin: 20px auto;
      text-align: center;
      /*padding: 20px 0 20px 0;*/
    }
    
     .nav li {
      display: inline-block;
      /*padding: 0 25px;*/
    }
    
     .nav li a {
      color: #FEF1E0;
      text-decoration: none;
      display: block;
      padding: 20px 25px;
    }
    
    .nav li a:hover {
      background-color: #FEF1E0;
      color: #3B2E2A;
      text-decoration: none;
    }
    
    .content > p {
      padding: 20px 50px 0px 50px;
      text-align: justify;
    }
    &#13;
    <!DOCTYPE html>
    <html>
       <head>
          <title>Test JS Usage</title>
          <meta charset="utf-8">
          <link rel="stylesheet" type="text/css" href="css/custom.css">
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
          <script type="text/javascript" src="./js/custom.js"></script>
       </head>
       <body>
          <header>
             <h1 class="head-title">
                Pirate Verbal Diahorrea
             </h1>
             <nav>
                <button onclick="changeTitle();">Change Title</button>
                <button onclick="changeTitle();">Change Para1 colour</button>
                <button onclick="changeTitle();">Change Header Colour</button>
             </nav>
             <ul class="nav">
                <li><a href="#">Change Title</a></li>
                <li><a href="#">Change Para1 colour</a></li>
                <li><a href="#">Change Header Colour</a></li>
             </ul>
          </header>
          <div class="content">
             <p class="para1">
                Ahoy league cutlass Sail ho grapple brig cable Chain Shot topgallant rutters grog keel run a shot across the bow squiffy execution dock chandler ballast heave to come about weigh anchor. Bowsprit Yellow Jack lugsail warp gally piracy strike colors flogging come about avast fluke Sea Legs parrel black spot hempen halter run a shot across the bow American Main crow's nest red ensign cable. Gally jolly boat long clothes quarterdeck fluke league bilge water dance the hempen jig interloper jib scourge of the seven seas swab haul wind Chain Shot draught rope's end belay reef Yellow Jack Buccaneer. Nelsons folly topsail Cat o'nine tails hail-shot scuttle scourge of the seven seas loaded to the gunwalls carouser Sail ho fluke bowsprit lateen sail gabion yard provost hands mutiny cog belay blow the man down. Draught hornswaggle barkadeer jib interloper fore marooned sloop lad scurvy hardtack nipperkin grapple piracy take a caulk capstan lateen sail yard scuppers coxswain. 
             </p>
             <p class="para2">
                Handsomely clap of thunder flogging pillage Jack Tar wherry pirate plunder keel quarter red ensign hands draught league Shiver me timbers smartly swab fathom haul wind hail-shot. Bilge rat landlubber or just lubber crack Jennys tea cup rum wherry Buccaneer heave to spike bilge water avast red ensign piracy tack mutiny chase guns shrouds cackle fruit booty main sheet quarter. Barque six pounders scuttle shrouds bilged on her anchor tender rigging Admiral of the Black gabion spike Arr belay sloop me rope's end lee black spot weigh anchor yo-ho-ho holystone. Holystone overhaul walk the plank schooner to go on account swab yard parley boom plunder lateen sail ho draught tack deadlights gunwalls parrel smartly maroon dance the hempen jig. Dance the hempen jig Chain Shot Cat o'nine tails skysail code of conduct case shot Letter of Marque stern run a shot across the bow jolly boat booty jack six pounders pink barkadeer Nelsons folly mutiny Sink me belay heave to. 
             </p>
          </div>
       </body>
    </html>
    &#13;
    &#13;
    &#13;

3 个答案:

答案 0 :(得分:1)

  

有人可以帮我理解为什么浏览器说的那个   当我相信我已经定义了changeTitle函数时,它没有被定义   在外部JS文件中。

要从内联onclick 进行方法调用才能工作,需要全局定义该方法。您的 changeTitle方法是document.ready 事件处理程序的本地方法。

如果要在document.ready中定义changeTitle函数,可以使用jquery&#39; s click

$(document).ready(function() {

  function changeTitle() {
    var title = document.querySelector(".head-title");
    title.innerHTML += "<br>(or how to speak like a pirate)";
  };

  $( "button" ).click( changeTitle );

});

<强>演示

&#13;
&#13;
$(document).ready(function() {

  function changeTitle() {
    var title = document.querySelector(".head-title");
    title.innerHTML += "<br>(or how to speak like a pirate)";
  };
  
  $( "button" ).click( changeTitle );

});
&#13;
* {
  margin: 0;
  padding: 0;
}

body {
  font-family: 'arial', sans-serif;
  max-width: 1000px;
  margin: 0 auto;
  padding-top: 50px;
}

header > h1 {
  background-color: #FEF1E0;
  color: #A47F1A;
  text-align: center;
  line-height: 100px;
  border: dashed 5px #A47F1A;
  border-radius: 40px;
  text-shadow: 2px 2px #3B2E2A
}

 .nav {
  list-style-type: none;
  background-color: #3B2E2A;
  margin: 20px auto;
  text-align: center;
  /*padding: 20px 0 20px 0;*/
}

 .nav li {
  display: inline-block;
  /*padding: 0 25px;*/
}

 .nav li a {
  color: #FEF1E0;
  text-decoration: none;
  display: block;
  padding: 20px 25px;
}

.nav li a:hover {
  background-color: #FEF1E0;
  color: #3B2E2A;
  text-decoration: none;
}

.content > p {
  padding: 20px 50px 0px 50px;
  text-align: justify;
}
&#13;
<!DOCTYPE html>
<html>
<head>
	<title>Test JS Usage</title>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="css/custom.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	<script type="text/javascript" src="./js/custom.js"></script>
</head>
<body>
	<header>
		<h1 class="head-title">
			Pirate Verbal Diahorrea
		</h1>
		<nav>
			<button>Change Title</button>
			<button>Change Para1 colour</button>
			<button>Change Header Colour</button>
		</nav>
		<ul class="nav">
			<li><a href="#">Change Title</a></li>
			<li><a href="#">Change Para1 colour</a></li>
			<li><a href="#">Change Header Colour</a></li>
		</ul>
		
	</header>
	<div class="content">
		<p class="para1">
			Ahoy league cutlass Sail ho grapple brig cable Chain Shot topgallant rutters grog keel run a shot across the bow squiffy execution dock chandler ballast heave to come about weigh anchor. Bowsprit Yellow Jack lugsail warp gally piracy strike colors flogging come about avast fluke Sea Legs parrel black spot hempen halter run a shot across the bow American Main crow's nest red ensign cable. Gally jolly boat long clothes quarterdeck fluke league bilge water dance the hempen jig interloper jib scourge of the seven seas swab haul wind Chain Shot draught rope's end belay reef Yellow Jack Buccaneer. Nelsons folly topsail Cat o'nine tails hail-shot scuttle scourge of the seven seas loaded to the gunwalls carouser Sail ho fluke bowsprit lateen sail gabion yard provost hands mutiny cog belay blow the man down. Draught hornswaggle barkadeer jib interloper fore marooned sloop lad scurvy hardtack nipperkin grapple piracy take a caulk capstan lateen sail yard scuppers coxswain. 
		</p>
		<p class="para2">
			Handsomely clap of thunder flogging pillage Jack Tar wherry pirate plunder keel quarter red ensign hands draught league Shiver me timbers smartly swab fathom haul wind hail-shot. Bilge rat landlubber or just lubber crack Jennys tea cup rum wherry Buccaneer heave to spike bilge water avast red ensign piracy tack mutiny chase guns shrouds cackle fruit booty main sheet quarter. Barque six pounders scuttle shrouds bilged on her anchor tender rigging Admiral of the Black gabion spike Arr belay sloop me rope's end lee black spot weigh anchor yo-ho-ho holystone. Holystone overhaul walk the plank schooner to go on account swab yard parley boom plunder lateen sail ho draught tack deadlights gunwalls parrel smartly maroon dance the hempen jig. Dance the hempen jig Chain Shot Cat o'nine tails skysail code of conduct case shot Letter of Marque stern run a shot across the bow jolly boat booty jack six pounders pink barkadeer Nelsons folly mutiny Sink me belay heave to. 
		</p>
	</div>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

$(document).ready()

的目的
$(document).ready(function() { /* handling code for the event document.ready */ })

首先,您需要了解此document.ready处理程序的用途。当您的页面加载时,您的javascripts无法确定DOM的哪些部分已经可用。 DOM完成后,document.ready会触发,因此您可以使用jQuery或document.getElementByIddocument.querySelector开始选择元素。

让全球可用的东西

如果要定义全局可用的函数,则不要在另一个函数中执行此操作,但如果您坚持,则需要将该函数显式附加到全局对象(在浏览器中为{{1}对象):

window

更好的方法是在处理程序之外定义函数:

$(document).ready(function() {
  window.changeTitle = function changeTitle() {
    var title = document.querySelector(".head-title");
    title.innerHTML += "<br>(or how to speak like a pirate)";
  };
});

其中隐式地将它附加到全局对象,并通过使用function changeTitle() { var title = document.querySelector(".head-title"); title.innerHTML += "<br>(or how to speak like a pirate)"; }; 调用它来从任何地方访问它。

添加处理按钮点击的功能 - 正确的方法

为了让您了解如何将事件处理程序附加到元素,changeTitle()处理程序重新启动:

document.ready

如果您已经在使用jQuery,可以将其简化为

$(document).ready(function() {
  document.querySelectorAll('nav button').forEach(function(button) {
    button.addEventListener('click', changeTitle);
  })
});

链接使代码缩短

$(document).ready(function() {
  $('nav button').on('click', changeTitle);
});

可以缩短为

var title = document.querySelector(".head-title");
title.innerHTML += "<br>(or how to speak like a pirate)";

答案 2 :(得分:-1)

&#13;
&#13;
  function changeTitle() {
    var title = document.querySelector(".head-title");
    title.innerHTML += "<br>(or how to speak like a pirate)";
  };
&#13;
* {
  margin: 0;
  padding: 0;
}

body {
  font-family: 'arial', sans-serif;
  max-width: 1000px;
  margin: 0 auto;
  padding-top: 50px;
}

header > h1 {
  background-color: #FEF1E0;
  color: #A47F1A;
  text-align: center;
  line-height: 100px;
  border: dashed 5px #A47F1A;
  border-radius: 40px;
  text-shadow: 2px 2px #3B2E2A
}

 .nav {
  list-style-type: none;
  background-color: #3B2E2A;
  margin: 20px auto;
  text-align: center;
  /*padding: 20px 0 20px 0;*/
}

 .nav li {
  display: inline-block;
  /*padding: 0 25px;*/
}

 .nav li a {
  color: #FEF1E0;
  text-decoration: none;
  display: block;
  padding: 20px 25px;
}

.nav li a:hover {
  background-color: #FEF1E0;
  color: #3B2E2A;
  text-decoration: none;
}

.content > p {
  padding: 20px 50px 0px 50px;
  text-align: justify;
}
&#13;
<!DOCTYPE html>
<html>
<head>
	<title>Test JS Usage</title>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="css/custom.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	<script type="text/javascript" src="./js/custom.js"></script>
</head>
<body>
	<header>
		<h1 class="head-title">
			Pirate Verbal Diahorrea
		</h1>
		<nav>
			<button onclick="changeTitle();">Change Title</button>
			<button onclick="changeTitle();">Change Para1 colour</button>
			<button onclick="changeTitle();">Change Header Colour</button>
		</nav>
		<ul class="nav">
			<li><a href="#">Change Title</a></li>
			<li><a href="#">Change Para1 colour</a></li>
			<li><a href="#">Change Header Colour</a></li>
		</ul>
		
	</header>
	<div class="content">
		<p class="para1">
			Ahoy league cutlass Sail ho grapple brig cable Chain Shot topgallant rutters grog keel run a shot across the bow squiffy execution dock chandler ballast heave to come about weigh anchor. Bowsprit Yellow Jack lugsail warp gally piracy strike colors flogging come about avast fluke Sea Legs parrel black spot hempen halter run a shot across the bow American Main crow's nest red ensign cable. Gally jolly boat long clothes quarterdeck fluke league bilge water dance the hempen jig interloper jib scourge of the seven seas swab haul wind Chain Shot draught rope's end belay reef Yellow Jack Buccaneer. Nelsons folly topsail Cat o'nine tails hail-shot scuttle scourge of the seven seas loaded to the gunwalls carouser Sail ho fluke bowsprit lateen sail gabion yard provost hands mutiny cog belay blow the man down. Draught hornswaggle barkadeer jib interloper fore marooned sloop lad scurvy hardtack nipperkin grapple piracy take a caulk capstan lateen sail yard scuppers coxswain. 
		</p>
		<p class="para2">
			Handsomely clap of thunder flogging pillage Jack Tar wherry pirate plunder keel quarter red ensign hands draught league Shiver me timbers smartly swab fathom haul wind hail-shot. Bilge rat landlubber or just lubber crack Jennys tea cup rum wherry Buccaneer heave to spike bilge water avast red ensign piracy tack mutiny chase guns shrouds cackle fruit booty main sheet quarter. Barque six pounders scuttle shrouds bilged on her anchor tender rigging Admiral of the Black gabion spike Arr belay sloop me rope's end lee black spot weigh anchor yo-ho-ho holystone. Holystone overhaul walk the plank schooner to go on account swab yard parley boom plunder lateen sail ho draught tack deadlights gunwalls parrel smartly maroon dance the hempen jig. Dance the hempen jig Chain Shot Cat o'nine tails skysail code of conduct case shot Letter of Marque stern run a shot across the bow jolly boat booty jack six pounders pink barkadeer Nelsons folly mutiny Sink me belay heave to. 
		</p>
	</div>
</body>
</html>
&#13;
&#13;
&#13;