Jump to content
  • Sign Up
  • 0

Не определяет элемент lastChild


Stojan
 Share

Question

Уважаемые форумчане!
Просьба помочь со скриптом.
Краткая информация о скрипте:
1. Скрипт генерит 5 элементов img и добавляет их в один из двух пустых div.
2. Скрипт копирует все элементы из одного div в другой, при этом удаляя один элемент img. Получаем 5 и 4 элемента img в двух div.
До этого момента все гладко.

Далее скрипт должен при нажатии на lastChild левого div, которым является один из img удалять всех child из обоих div и генерить уже 10 и 9 соответственно (по схеме выше).

Или, при нажатии на любой другой child в div кроме последнего, выдавать сообщение. 

Вот проблема заключается в том, что не получается прописать событие onclick на последнем child'e одного из div, чтобы произошел вызов функции.

Заранее благодарю за помощь.

Это проблемный участок скрипта:

""""

theLeftSide.lastChild.onclick= function nextLevel(){

// onclick.stopPropagation();
numberOfFaces += 5;
//delete all childNodes
while(theBody.firstChild){theBody.removeChild(theB ody.firstChild);
generateFaces();
}}

""""

 

Весь скрипт:

<!doctype html>
<html>
<head>
<style>
#rightSide { left: 500px;
            border-left: 2px solid black;
            width:500px; height:500px;
            position:absolute ;}
#leftSide {width:500px; height:500px;position:absolute;}
img{position:absolute;}
</style>
<meta charset="utf-8">
<title>Matching Game</title>
<script>
numberOfFaces =5;
theLeftSide=document.getElementById("leftSide");
theRightSide =document.getElementById("rightSide");
theBody = document.getElementsByTagName("body")[0];
 
 
function generateFaces() {
//1st   for(i=1;i<=numberOfFaces;i++){
//2nd
    var     i=1;
    while(i<=numberOfFaces){
// 
var image=document.createElement("img");
    image.src="smile.png";
    image.style.top=Math.floor(Math.random()*401)+"px";
    image.style.left=Math.floor(Math.random()*401)+"px";
    leftSide.appendChild(image);
    i++;
}
var leftSideImages = leftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
rightSide.appendChild(leftSideImages);
//part3 end
 
}
 
theLeftSide.lastChild.onclick= function nextLevel(){
     // onclick.stopPropagation();
     numberOfFaces += 5;
//delete all childNodes
while(theBody.firstChild){theBody.removeChild(theBody.firstChild);
generateFaces();
}
}
theBody.onclick = function gameOver() {
    alert("Game Over!");
    theBody.onclick = null;
    theLeftSide.lastChild.onclick = null;
}
</script>
</head>
<body onLoad="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>

 

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

Так вы же пытаетесь повесить обработчик на несуществующую ноду, а только потом генерируете картинки.

Либо делайте это после, но лучше, как указал Great Rash, использовать делегирование.

Link to comment
Share on other sites

  • 0

1) запилите живой пример на codepen.io

2) если у вас чилды всё время меняются, то и обработчик события нужно всё время заново устанавливать, а можно тупо делегирование использовать вместо того, чтобы прям на чилда вешать обработчик.

Link to comment
Share on other sites

  • 0

Ок. Спасибо! Попробую разобраться с делегированием.

 

А почему после того, как функция generateFaces() сработала при загрузке (создав 5 элементов img в левом div), не находится ни один child у элемента div?

Link to comment
Share on other sites

  • 0

Решил задачу следующим образом:

 

<html>
<head>
<style>
#rightSide { left: 500px; 
            border-left: 2px solid black;
width:500px; height:500px;
position:absolute ;}
#leftSide {width:500px; height:500px;position:absolute;}
img{position:absolute;}
</style>
<meta charset="utf-8">
<title>Matching Game</title>
<script>
 numberOfFaces =5;
var level=1;
 
function generateFaces() {
theLeftSide=document.getElementById("leftSide");
 theRightSide =document.getElementById("rightSide");
 theBody = document.getElementsByTagName("body")[0];
 
var i=1;
while(i<=numberOfFaces){
 
image=document.createElement("img");
image.src="smile.png";
image.style.top=Math.floor(Math.random()*401)+"px";
image.style.left=Math.floor(Math.random()*401)+"px";
    theLeftSide.appendChild(image);
i++;
}
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
theLeftSide.lastChild.onclick= function nextLevel(event){
    event.stopPropagation();
 
level++;
     numberOfFaces += 5;
 
//delete all childNodes
alert("Right! Proceeding to the "+level+" level!");
while(theLeftSide.firstChild){theLeftSide.removeChild(theLeftSide.firstChild);}
while(theRightSide.firstChild){theRightSide.removeChild(theRightSide.firstChild);}
generateFaces();
 
}
theBody.onclick = function gameOver() {
    alert("Game Over! You've reached only "+level+" level");
    theBody.onclick = null;
    theLeftSide.lastChild.onclick = null;
}
}
 
</script>
</head>
<body onLoad="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div> 
<div id="rightSide"></div> 
 
</body>
</html>
 
Вставил функцию с событием onclick в функцию генерирования чайлдов.
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Similar Content

    • Kaido
      By Kaido
      Использую готовый плагин для модальных окон(от MaxGraph). Проблема в том, что когда у меня открыто два модальных окна, для примера Форма + Политика конфендициальности, и мне нужно закрыть политику вместе с ней закрывается и другое модальное окно. В JS я не сильно разбираюсь(собственно из за этого и использую готовый плагин), можете помочь кто работал с этим плагином? Я примерно понимаю как он работает, но реализовать чтобы закрывалось только одно не получается.
       
        <div class="content"> <button class="modal-btn" data-path="first" data-animation="fadeInUp" data-speed="1500">Открыть окно 1</button> </div> <div class="modal"> <div class="modal__wrapp" data-target="first"> <div class="modal__content"> <button class="modal__close">Закрыть</button> модальное окно <button data-path="policy">Политика</button> </div> </div> <div class="modal__wrapp" data-target="policy"> <div class="modal__content"> <button class="modal__close">Закрыть</button> политика </div> </div> </div> .modal { --transition-time: 0.3s; position: fixed; left: 0; top: 0; right: 0; bottom: 0; z-index: 1000; cursor: pointer; overflow-y: auto; overflow-x: hidden; text-align: center; opacity: 0; visibility: hidden; transition: opacity var(--transition-time), visibility var(--transition-time); } .modal__wrapp { display: none; cursor: default; width: fit-content; height: fit-content; } .modal__content{ position: absolute; left: 500px; width: 500px; height: 500px; display: flex; color: white; flex-direction: column; text-align: left; background-color: #000; } .modal__content button{ width: 200px; height: 50px; margin: 50px 0; } .modal.is-open { opacity: 1; visibility: visible; transition: opacity var(--transition-time), visibility var(--transition-time); } .modal__wrapp.modal-open { display: flex; } .disable-scroll { position: relative; overflow: hidden; height: 100vh; position: fixed; left: 0; top: 0; width: 100%; } .fade { opacity: 0; transition: opacity var(--transition-time); } .fade.animate-open { opacity: 1; transition: opacity var(--transition-time); } .fadeInUp { opacity: 0; transform: translateY(vw(-100)); transition: opacity var(--transition-time), transform var(--transition-time); } .fadeInUp.animate-open { opacity: 1; transform: translateY(0); transition: opacity var(--transition-time), transform var(--transition-time); } .modal__wrapp[data-target="policy"] .modal__content{ left: 1050px; background-color: #000; opacity: .5; } class Modal { constructor(options) { let defaultOptions = { isOpen: () => {}, isClose: () => {}, } this.options = Object.assign(defaultOptions, options); this.modal = document.querySelector('.modal'); this.speed = false; this.animation = false; this.isOpen = false; this.modalContainer = false; this.previousActiveElement = false; this.fixBlocks = document.querySelectorAll('.fix-block'); this.focusElements = [ 'a[href]', 'input', 'button', 'select', 'textarea', '[tabindex]' ]; this.events(); } events() { if (this.modal) { document.addEventListener('click', function(e){ const clickedElement = e.target.closest('[data-path]'); if (clickedElement) { let target = clickedElement.dataset.path; let animation = clickedElement.dataset.animation; if (clickedElement.classList.contains('modal-close')) { this.close(); } let speed = clickedElement.dataset.speed; this.animation = animation ? animation : 'fade'; this.speed = speed ? parseInt(speed) : 300; this.modalContainer = document.querySelector(`[data-target="${target}"]`); this.open(); return; } if (e.target.closest('.modal__close')) { this.close(); return; } }.bind(this)); window.addEventListener('keydown', function(e) { if (e.keyCode == 27) { if (this.isOpen) { this.close(); } } if (e.keyCode == 9 && this.isOpen) { this.focusCatch(e); return; } }.bind(this)); this.modal.addEventListener('click', function(e) { if (!e.target.classList.contains('modal__wrapp') && !e.target.closest('.modal__wrapp') && this.isOpen) { this.close(); } }.bind(this)); } } open() { this.previousActiveElement = document.activeElement; this.modal.style.setProperty('--transition-time', `${this.speed / 1000}s`); this.modal.classList.add('is-open'); this.disableScroll(); this.modalContainer.classList.add('modal-open'); this.modalContainer.classList.add(this.animation); setTimeout(() => { this.options.isOpen(this); this.modalContainer.classList.add('animate-open'); this.isOpen = true; this.focusTrap(); }, this.speed); } close() { if (this.modalContainer) { this.modalContainer.classList.remove('animate-open'); this.modalContainer.classList.remove(this.animation); this.modal.classList.remove('is-open'); this.modalContainer.classList.remove('modal-open'); this.enableScroll(); this.options.isClose(this); this.isOpen = false; this.focusTrap(); } } focusCatch(e) { const focusable = this.modalContainer.querySelectorAll(this.focusElements); const focusArray = Array.prototype.slice.call(focusable); const focusedIndex = focusArray.indexOf(document.activeElement); if (e.shiftKey && focusedIndex === 0) { focusArray[focusArray.length - 1].focus(); e.preventDefault(); } if (!e.shiftKey && focusedIndex === focusArray.length - 1) { focusArray[0].focus(); e.preventDefault(); } } focusTrap() { const focusable = this.modalContainer.querySelectorAll(this.focusElements); if (this.isOpen) { focusable[0].focus(); } else { this.previousActiveElement.focus(); } } disableScroll() { let pagePosition = window.scrollY; this.lockPadding(); document.body.classList.add('disable-scroll'); document.body.dataset.position = pagePosition; document.body.style.top = -pagePosition + 'px'; } enableScroll() { let pagePosition = parseInt(document.body.dataset.position, 10); this.unlockPadding(); document.body.style.top = 'auto'; document.body.classList.remove('disable-scroll'); window.scroll({ top: pagePosition, left: 0 }); document.body.removeAttribute('data-position'); } lockPadding() { let paddingOffset = window.innerWidth - document.body.offsetWidth + 'px'; this.fixBlocks.forEach((el) => { el.style.paddingRight = paddingOffset; }); document.body.style.paddingRight = paddingOffset; } unlockPadding() { this.fixBlocks.forEach((el) => { el.style.paddingRight = '0px'; }); document.body.style.paddingRight = '0px'; } } const modal = new Modal({ isOpen: (modal) => { console.log(modal); console.log('opened'); }, isClose: () => { console.log('closed'); }, });  
    • ilyamio
      By ilyamio
      Здравствуйте. Имеется рабочий скрипт конвертера валют. https://ilyamio.github.io/currencyconverter/
      Мне необходимо изменить источник загрузки курсов на ЦБ РФ вот по этой ссылке: https://www.cbr.ru/scripts/XML_daily.asp
      А также мне необходимо установить ограничение на количество обращений к сайту ЦБ РФ - 1 раз в сутки. При частом обращении, могут заблокировать.
      Вот в этом js файле находятся настройки конвертера:
      const from_currencyEl = document.getElementById('from_currency'); const from_ammountEl = document.getElementById('from_ammount'); const to_currencyEl = document.getElementById('to_currency'); const to_ammountEl = document.getElementById('to_ammount'); const rateEl = document.getElementById('rate'); const exchange = document.getElementById('exchange'); from_currencyEl.addEventListener('change', calculate); from_ammountEl.addEventListener('input', calculate); to_currencyEl.addEventListener('change', calculate); to_ammountEl.addEventListener('input', calculate); exchange.addEventListener('click', () => { const temp = from_currencyEl.value; from_currencyEl.value = to_currencyEl.value; to_currencyEl.value = temp; calculate(); }); function calculate() { const from_currency = from_currencyEl.value; const to_currency = to_currencyEl.value; fetch(`https://api.exchangerate-api.com/v4/latest/${from_currency}`) .then(res => res.json()) .then(res => { const rate = res.rates[to_currency]; rateEl.innerText = `1 ${from_currency} = ${rate} ${to_currency}` to_ammountEl.value = (from_ammountEl.value * rate).toFixed(2); }) } calculate(); Как мне изменить настройки в этом файле чтобы курсы брались с https://www.cbr.ru/scripts/XML_daily.asp и включить ограничение на количество обращений по ссылке cbr.ru - 1 раз в сутки?
      Заранее спасибо всем, кто хотел помочь с решением этой задачи.
    • vasyl_runner
      By vasyl_runner
      $(function () { var mixer = mixitup('.directions__list'); $('.directions__filter-btn').on('click', function () { $('.directions__filter-btn').removeClass('directions__filter-btn--active') $(this).addClass('directions__filter-btn--active') }) })
    • Yurich
      By Yurich
      Всем привет, у меня такой вот вопрос, делаю сайт через react и при изменении расширения что-то идёт не так и какой-то бред получается, подскажите как решить данную проблему. Я вообще не понимаю из-за чего это происходит, по этому не могу нормально объяснить 😅.

    • bromble
      By bromble
      Всем привет!
      Может ли кто-нибудь сказать как реализована такая каруселька у элементов каталога?
      MyVideo_55.mp4
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy