Изменение цвета текста с помощью JavaScript Object Constructor - PullRequest
0 голосов
/ 01 декабря 2018

Я новичок здесь и ценю несколько советов по этой проблеме, которые я пытаюсь выяснить.Я понимаю, что, возможно, есть лучшие способы сделать это без использования конструктора объектов, но я работаю над тем, чтобы лучше понять объекты.У меня вопрос, есть ли что-то вроде this.function, которая ссылается на все другие объекты, которые не вызывали мою функцию.Вот что я пытаюсь сделать:

<!doctype HTML>
<html>

<head>
  <title>Test</title>
  <style type="text/css">
    a {
      text-decoration: none;
      color: black;
    }
    
    a:visited {
      text-decoration: none;
      color: black;
    }
  </style>
</head>

<body>
  <ul>
    <li><a href="#" id="one"> Test</a> </li>
    <li><a href="#" id="two"> Test again</a> </li>
    <li><a href="#" id="three">Tester </a></li>
    <li><a href="#" id="four"> Testify</a> </li>
  </ul>
  <script>
    var first = document.getElementById('one');
    var second = document.getElementById('two');
    var third = document.getElementById('three');
    var fourth = document.getElementById('four');

    var colorChange = function(theID) {
      this.id = theID;
      this.formatContent = () => {
        this.id.style.color = "red";
      };
    }

    test = new colorChange(first);
    testAgain = new colorChange(second);
    tester = new colorChange(third);
    testify = new colorChange(fourth);

    function createEventListeners() {
      if (first.addEventListener) {
        first.addEventListener("click", test.formatContent, false);
      }
      if (second.addEventListener) {
        second.addEventListener("click", testAgain.formatContent, false);
      }
      if (third.addEventListener) {
        third.addEventListener("click", tester.formatContent, false);
      }
      if (fourth.addEventListener) {
        fourth.addEventListener("click", testify.formatContent, false);
      }
    }

    function init() {
      createEventListeners();
    }

    if (window.addEventListener) {
      //call init() on page load
      console.log("> Adding TC39 Event Listener...");
      window.addEventListener("load", init, false);
    } else if (window.attachEvent) {
      console.log("> Adding MS Event Listener...");
      window.attachEvent("onload", init);
    }
  </script>
</body>

</html>

Вы заметите, что при нажатии на один из элементов li он изменит свой цвет на красный.Проблема в том, что это не понятно, когда вы нажимаете другой li.Я думал, что я могу просто сказать браузеру изменить все другие объекты на черный при запуске formatContent ().Есть простой способ сделать это?

Вот ручка, если нужно: https://codepen.io/seanbarker182/pen/JexPVz

Спасибо за любую помощь заранее!

Ответы [ 3 ]

0 голосов
/ 01 декабря 2018

Существует несколько более простой способ добиться этого, когда вам не нужны идентификаторы, и вам нужно установить только один прослушиватель событий.

Вот урезанный пример:

// Grab the main ul element and attach a click
// listener to it. This will listen to events that
// bubble up the DOM from other clicked elements
// (event propagation)
const ul = document.querySelector('ul');
ul.addEventListener('click', handleClick, false);

// Grab the list items
const lis = document.querySelectorAll('ul li');

function handleClick(e) {

  // Grab the classList property from the event target
  const { classList } = e.target;

  // Loop over the list items a reset their color
  [...lis].forEach(li => li.classList.remove('active'));

  // add a red class to the clicked element
  classList.add('active');
}
.active { background-color: red; }
<ul class="colors">
  <li>Test</li>
  <li>Test again</li>
  <li>Tester</li>
  <li>Testify</li>
</ul>
0 голосов
/ 01 декабря 2018

Если вы сделаете это, чтобы узнать об объектах, использование prototype - это один из способов получить то, что вы хотите:

var colorChange = function (theID) {
  this.id = theID;
  this.instances.push(this);
  this.formatContent = () => {
  this.revertColors();
  this.id.style.color = "red"
  };
}

colorChange.prototype.instances = [];
colorChange.prototype.revertColors = function() {
  this.instances.forEach(instance => (instance.id.style.color = "black"))
}

Этот код хранит экземпляры объекта prototype, который используется всемиэкземпляры классов при инициализации.Вы можете обращаться к этому массиву из любого экземпляра и вносить необходимые изменения.

var first = document.getElementById('one');
var second = document.getElementById('two');
var third = document.getElementById('three');
var fourth = document.getElementById('four');

var colorChange = function (theID) {
	this.id = theID;
  this.instances.push(this);
  this.formatContent = () => {
  this.revertColors();
  this.id.style.color = "red"
  };
}

colorChange.prototype.instances = [];
colorChange.prototype.revertColors = function() {
  this.instances.forEach(instance => (instance.id.style.color = "black"))
}

test = new colorChange(first);
testAgain = new colorChange(second);
tester = new colorChange(third);
testify = new colorChange(fourth);

function createEventListeners() {
   if (first.addEventListener) {
    first.addEventListener("click", test.formatContent, false);
  } if (second.addEventListener) {
    second.addEventListener("click", testAgain.formatContent, false);
  } if (third.addEventListener) {
    third.addEventListener("click", tester.formatContent, false);
  } if (fourth.addEventListener) {
    fourth.addEventListener("click", testify.formatContent, false);
  }
}

function init(){
	createEventListeners();
}

if (window.addEventListener) {
  //call init() on page load
   console.log("> Adding TC39 Event Listener...");
   window.addEventListener ("load", init, false);
}
else if (window.attachEvent) {
   console.log("> Adding MS Event Listener...");
   window.attachEvent ("onload", init);
}
a {
  text-decoration: none;
  color: black;
}

a:visited {
  text-decoration: none;
	color: black;
}
<html>
<head>
	<title>Test</title>
</head>
<body>
<ul>
	<li><a href="#0" id="one"> Test</a> </li>
	<li><a href="#0" id="two"> Test again</a> </li>
	<li><a href="#0" id="three">Tester </a></li>
	<li><a href="#0" id="four"> Testify</a> </li>
</ul>
</body>
</html>
0 голосов
/ 01 декабря 2018

Просто измените ваш formatContent метод:

this.formatContent = () => {
    if (this.id.style.color == "black") {
        this.id.style.color = "red";
    } else {
        this.id.style.color = "black";
    }
};

РЕДАКТИРОВАТЬ:

Чтобы сделать только красный цвет, по которому щелкнули, сначала создайте массив:

var elements = [first, second, third, fourth];

Затем зациклите его в функции и установите их все в черный цвет:

this.formatContent = () => {
    elements.forEach(function(elem) {
        elem.style.color = "black";
    }
    this.id.style.color = "red";
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...