为什么我的函数不更改属性tavelBanner的文本?

时间:2018-10-12 23:05:38

标签: javascript html dom

// My Html
     <body>
      <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="#"><span id = "travelBanner">Travel 
         City</span> 
        </a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" 
         data- 
       target="#navbarSupportedContent" aria- 
        controls="navbarSupportedContent" 
        aria- 
         expanded="false" aria-label="Toggle navigation">
       <span class="navbar-toggler-icon"></span>
     </button>

//为什么我的文本不会在网页上更改,但是在控制台日志中会更改?

//我正在尝试更改tavelBanner的文本。

     var travelNow = function(){

       var travelBanner = document.getElementById("travelBanner").
          textContent = "Discount";   }
       travelNow();
// when i console log the function the value is sent to the console.
      console.log(travelBanner);

1 个答案:

答案 0 :(得分:-1)

我希望这对您有用。运行代码片段,看看是否可以使用它。 ;)

  function discont() {
    const x = document.getElementById("travelBanner");
    if (x.innerHTML === "Travel city") {
        x.innerHTML = "Discount!";
    } else {
    x.innerHTML = "Travel city";
    }
  }
body {
  margin: 2rem;
  padding: 2rem;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

     <button class="btn-success"
             onclick="discont()"
             id="two">Discount
     </button>
     
     <div>
      <p class="navbar-brand" href="#"><span 
        id="travelBanner">Travel city</span> 
      </p>
     </div>