喜欢/不喜欢超链接不能以面向对象的方式工作吗?

时间:2019-02-27 17:37:20

标签: javascript html oop

我想要一个喜欢/不喜欢的超链接来在页面上显示不同的内容:单击“喜欢”时,显示“好”;单击“不喜欢”时,显示“不好”。我的代码是这样的:

<html>
<head>
<script>
function Homepage(){

    this.like = document.getElementById("like");
    this.dislike = document.getElementById("dislike");

    Homepage.prototype = {
        constructor: Homepage,
        likeGame: function(event){
            if(this.like.style.display == "none"){
                this.like.style.display = "block";
            }
            event.preventDefault();
            },
        dislikeGame: function(event){
            if(this.dislike.style.display == "none"){
                this.dislike.style.display = "block";
            }
            event.preventDefault();
            },
        setListeners: function(){
            console.log('in listen');
            document.getElementById("hyperLike").addEventListener("click", this.likeGame);
            document.getElementById("hyperDislike").addEventListener("click", this.dislikeGame);
        }
    }
}
</script>

</head>
<body>
<p style="display:block">
<a id="hyperLike" href="";>Like</a>/<a id="hyperDislike" href="";>Dislike</a> the game.
</p>
<p id="like" style="display:none">
good
</p>
<p id="dislike" style="display:none">
bad
</p>
<script>
var homepage = new Homepage();

window.onload = homepage.setListeners;
</script>
</body>
</html>

但是它不起作用。单击超链接没有反应。我在console.log中添加了setListeners,但未记录任何内容,因此它甚至都没有进入setListeners。这是什么问题?

我还有另一个none-OO版本,基本上是相同的代码,它可以工作。

2 个答案:

答案 0 :(得分:1)

问题在于this.like函数中的likeGame()this.like函数中的Homepage()不同,因为一个函数具有自己的作用域。解决此问题的一种方法是将箭头函数用作方法。现在this将始终引用Homepage

function Homepage() {

  this.like = document.getElementById("like");
  this.dislike = document.getElementById("dislike");


  this.likeGame = (event) => {

    if (this.like.style.display == "none") {
      this.dislike.style.display = "none"
      this.like.style.display = "block";
    }
    event.preventDefault();
  };
  this.dislikeGame = (event) => {
    if (this.dislike.style.display == "none") {
      this.like.style.display = "none"
      this.dislike.style.display = "block";
    }
    event.preventDefault();
  };
  this.setListeners = () => {
    console.log('in listen');
    document.getElementById("hyperLike").addEventListener("click", this.likeGame);
    document.getElementById("hyperDislike").addEventListener("click", this.dislikeGame);
  }
}

var homepage = new Homepage();

window.addEventListener("load", () => {
  homepage.setListeners();
})
<html>

<body>
  <p style="display:block">
    <a id="hyperLike" href="">Like</a>/<a id="hyperDislike" href="" ;>Dislike</a> the game.
  </p>
  <p id="like" style="display:none">
    good
  </p>
  <p id="dislike" style="display:none">
    bad
  </p>

</body>

</html>

答案 1 :(得分:0)

以下演示可以将多个元素绑定到任何适用的事件和回调函数。使用此类的优点是参数selectoreventcallback可以是任何东西,并且无需为多个侦听器采取额外的步骤。


演示

详细信息在演示中被评论

这是对此article 中的代码的修改。

// Define class
class Homepage {
  // Pass a CSS selector
  constructor(selector) {
    // Reference selector
    const elements = document.querySelectorAll(selector);
    // Get amount of elements
    this.length = elements.length;
    // Merge the constructor and elements
    Object.assign(this, elements);
  }
  // Pass a callback function
  each(callback) {
    // Iterate elements...
    for (let node of Array.from(this)) {
      // ...call callback function fore each element...
      callback.call(node);
    }
    // ...make the method chainable
    return this;
  }
  // Pass event and callback
  bind(event, callback) {
    // Iterate constructor...
    return this.each(function() {
      // ...regiter each element to the event and assign callback
      this.addEventListener(event, callback, false);
    });
  }
};

// Instantiate Homepage class
const likeHate = selector => new Homepage(selector);
// Callback rate()
const rate = e => {
  // Reference clicked element
  const tgt = e.target;
  // If the clicked has .btn class...
  if (tgt.matches('.btn')) {
    // ...get the clicked value...
    const val = e.target.value;
    // ...reference article#rate...
    const rate = document.getElementById('rate');
    // ...assign the value of clicked to [data-rate] of #rate
    rate.dataset.rate = val;
    // If the value of clicked is 'Superior' =  thumbs up/down
    let icon = val === 'Superior' ? '' : '';
    // Assign icon to [data-icon] of #rate
    rate.dataset.icon = icon;
  }
}
/*
Call the .bind() method on all .btn and register the click event
to each .btn. Assign rate() as callback function.
*/
likeHate('.btn').bind('click', rate);
html,
body {
  font: 700 16px/1.3 Raleway;
}

header {
  font-size: 1.5rem;
  margin: 10px 0;
}

.btn {
  border: 0 none transparent;
  background: none;
  cursor: pointer;
  font: inherit;
  margin: 0;
}

.btn:hover {
  color: blue;
  text-decoration: underline;
}

.btn:focus {
  outline: none;
}

#rate {
  font-size: 1.5rem;
}

#rate::before {
  content: attr(data-icon)'\a0';
}

#rate::after {
  content: attr(data-rate)'\a0';
}
<!DOCTYPE html>
<html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
</head>

<body>
  <header>
    <button class='btn' value='Superior'>Like</button>/<button class='btn' value='Inferior'>Hate</button> the game.
  </header>
  <article id="rate" data-icon='' data-rate=''></article>
</body>

</html>