Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

arnold avatar arnold 50 Точки

Problem 1. Pet Me (DOM Manipulation) - JS Advanced: Exam Preparation 

Вече се отчаях с тази задача, какво ли не гледам, дава ми 37/100, имам чувството, че просто judge иска да бъде решена по определен генериран начин. Ако някой може да помогне къде греша, ще съм много благодарен. На втори и трети тест единствено ми показва:

 2."Unexpected error: Cannot read property 'children' of undefined"

3. "Unexpected error: Cannot set property 'value' of null"

 

https://pastebin.com/AKEyqwmd

Условието и ресурса с готовия HTML са в judge:

Link in Judge: https://judge.softuni.org/Contests/Practice/Index/2469#0

 

Тагове:
0
JavaScript Advanced 18/02/2022 01:04:19
Axiomatik avatar Axiomatik 2422 Точки

Similar problem commented by https://softuni.bg/forum/31414/js-advanced-exam-27-06-2020-pet-me.

nickwork =>

Целият проблем в твоето решение е начина на създаване на елементите...не знам защо judge не го приема по този начин. Променил съм единствено това и нищо друго..внимавай на изпита с тази функция

Try using innerHTML instead of createTextNode for example, hard to say where exactly judge fails to work correctly with given DOM-element.

Demo code:

function solve() {
    // TODO ...

    const addButton = document.querySelector('#container button');
    const nameField = document.querySelector('#container input[placeholder="Name"]');
    const ageField = document.querySelector('#container input[placeholder="Age"]');
    const kindField = document.querySelector('#container input[placeholder="Kind"]');
    const currOwnerField = document.querySelector('#container input[placeholder="Current Owner"]');

    const adoptionField = document.querySelector('#adoption ul');
    const takenField = document.querySelector('#adopted ul');

    // console.log(addButton, nameField, ageField, kindField, currOwnerField);
    addButton.addEventListener('click', addNewPet);

    function addNewPet(event) {
        event.preventDefault();

        const name = nameField.value;
        let age = Number(ageField.value);
        const kind = kindField.value;
        const currOwner = currOwnerField.value;
        // age = Number(age);

        // nameField.value = '';
        // ageField.value = '';
        // kindField.value = '';
        // currOwnerField.value = '';

        const allFields = name.trim() !== ''
            && ageField.value.trim() !== ''
            && kind.trim() !== ''
            && currOwner.trim() !== '';

        const notNumber = Number.isNaN(age);

        if (allFields === false || notNumber === true) {
            return;
        }


        const newPet = createPetElement(name, age, kind, currOwner);
        adoptionField.appendChild(newPet);

        nameField.value = '';
        ageField.value = '';
        kindField.value = '';
        currOwnerField.value = '';
    }

    function createPetElement(name, age, kind, currOwner) {
        const resultLi = document.createElement('li');
        const paraInfo = document.createElement('p');
        const strongName = document.createElement('strong');
        strongName.textContent = name;
        const strongAge = document.createElement('strong');
        strongAge.textContent = age;
        const strongKind = document.createElement('strong');
        strongKind.textContent = kind;

        // paraInfo.innerText += `${strongName} is a ${strongAge} year old ${strongKind}`;
        paraInfo.appendChild(strongName);
        paraInfo.innerHTML += ` is a `;
        paraInfo.appendChild(strongAge);
        paraInfo.innerHTML += ` year old `;
        paraInfo.appendChild(strongKind);

        // ${strongAge} year old ${strongKind}`;

        const spanOwner = document.createElement('span');
        spanOwner.textContent = `Owner: ${currOwner}`;
        const buttonContact = document.createElement('button')
        buttonContact.textContent = 'Contact with owner';

        buttonContact.addEventListener('click', (event) => contactOwner(event, buttonContact, resultLi));

        resultLi.appendChild(paraInfo);
        resultLi.appendChild(spanOwner);
        resultLi.appendChild(buttonContact);


        return resultLi;
    }

    function contactOwner(event, buttonContact, parentLi) {
        event.preventDefault();
        // const parentLi = event.target.parentElement;
        // event.target.textContent = 'Yes! I take it!';

        buttonContact.remove();
        const newDiv = document.createElement('div');
        const inputName = document.createElement('input');
        inputName.placeholder = 'Enter your names';
        const confirmButton = document.createElement('button');
        confirmButton.textContent = 'Yes! I take it!';

        newDiv.appendChild(inputName);
        newDiv.appendChild(confirmButton);
        parentLi.appendChild(newDiv);
        confirmButton.addEventListener('click', (event) => confirmNewOwner(event, inputName, parentLi));
    }

    function confirmNewOwner(event, inputName, parentLi) {
        event.preventDefault();

        const newOwnerName = inputName.value;
        inputName.value = '';
        // if (!newOwnerName.trim()) {
        if (!newOwnerName) {
            return;
        }

        const spanOwner = parentLi.querySelector('span');
        spanOwner.textContent = `New Owner: ${newOwnerName}`;
        // const oldButton = parentLi.querySelector('button');
        // oldButton.remove();

        const oldDiv = parentLi.querySelector('div');
        oldDiv.remove();

        const checkedButton = document.createElement('button');
        checkedButton.textContent = 'Checked';
        checkedButton.addEventListener('click', function () {
            parentLi.remove();
        });
        parentLi.appendChild(checkedButton);

        takenField.appendChild(parentLi);
    }
}

 

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.