Javascript - у меня есть два прослушивателя событий, которые запускают одну и ту же функцию глобальной области видимости, но один из них не работает ... почему? - PullRequest
0 голосов
/ 25 апреля 2020

Для некоторого контекста, я в настоящее время плохо знаком с Javascript и программированием в целом. В настоящее время я делаю список дел, используя vanilla javascript.

. Я хочу, чтобы пользователь мог добавить запись, нажав кнопку «+» или нажав клавишу ввода в поле ввода.

Определения:

let count = 0;
let getAdd = document.getElementById('add')
let getBackground = document.getElementById('background')
let getInputs = document.getElementsByClassName('input')
let getItems = document.getElementsByClassName('item')
let getName = document.getElementById('name')

Слушатель события «нажатие клавиши» работает, а слушатель события «нажатие» - нет. Вот часть вопроса:

function addevent() {
    if (document.getElementById('name').value === '') {
        alert("You need to type something in the input field first!")
        return
    }
    if (getItems.length == 0) {
        count += 1;
        getBackground.innerHTML = ''
        getBackground.style = null;
        getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
        getInputs[count - 1].innerHTML = document.getElementById('name').value
        let heightplus = getBackground.offsetHeight;
        getBackground.style.height = parseInt(heightplus + 35) + "px"
        document.getElementById('name').value = ''
    }
    else {
        count += 1
        getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
        getInputs[count - 1].innerHTML = document.getElementById('name').value
        let heightplus = getBackground.offsetHeight;
        getBackground.style.height = parseInt(heightplus + 35) + "px"
        document.getElementById('name').value = ''
    }
}

getAdd.addEventListener("click", addevent(), false);

getName.addEventListener("keypress", function enter(e) {
    if (e.keyCode === 13) {
        addevent();
    }
}, false);

Что мне здесь не хватает?

Если вам нужна дополнительная информация, дайте мне знать.

let count = 0;
let getAdd = document.getElementById('add')
let getBackground = document.getElementById('background')
let getInputs = document.getElementsByClassName('input')
let getItems = document.getElementsByClassName('item')
let getName = document.getElementById('name')

function noitems() {
    if (count == 0) {
        getBackground.innerHTML = '<div class="start">Click on the <strong>+</strong> button to get started</div>'
    }
    else if (count == -1) {
        getBackground.innerHTML = '<div class="end">No more tasks? Happy days!</div>'
        count += 1
    }
    getBackground.style.paddingTop = "0px"
    getBackground.style.boxShadow = "0px 0px 0px 0px"
    getBackground.style.backgroundColor = "white"
}

window.onload = noitems();

function addevent() {
    if (document.getElementById('name').value === '') {
        alert("You need to type something in the input field first!")
        return
    }
    if (getItems.length == 0) {
        count += 1;
        getBackground.innerHTML = ''
        getBackground.style = null;
        getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
        getInputs[count - 1].innerHTML = document.getElementById('name').value
        let heightplus = getBackground.offsetHeight;
        getBackground.style.height = parseInt(heightplus + 35) + "px"
        document.getElementById('name').value = ''
    }
    else {
        count += 1
        getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
        getInputs[count - 1].innerHTML = document.getElementById('name').value
        let heightplus = getBackground.offsetHeight;
        getBackground.style.height = parseInt(heightplus + 35) + "px"
        document.getElementById('name').value = ''
    }
}

getAdd.addEventListener("click", addevent(), false);

getName.addEventListener("keypress", function enter(e) {
    if (e.keyCode === 13) {
        addevent();
    }
}, false);

function doSomething(e) {
    if (e.target.id === "bin") {
        if (getItems.length == 1) {
            let clickeditem = e.target
            getBackground.removeChild(clickeditem.parentNode)
            count -= 2
            noitems();
        }
        else {
            let clickeditem = e.target
            getBackground.removeChild(clickeditem.parentNode)
            let heightminus = getBackground.offsetHeight;
            getBackground.style.height = parseInt(heightminus - 75) + "px"
            count -= 1
        }
    }
    e.stopPropagation();
}

getBackground.addEventListener("click", doSomething, false)
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap');
body {
    font-family: 'Roboto', sans-serif;
    -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Opera and Firefox */
}
#title {
    font-size: 32px;
    margin-top: 1em;
    border: 5px;
    border-style: solid;
    border-color: #001F5F;
    width: 9em;
    margin-left: calc(50% - 4.6em);
    margin-right: calc(50% - 4.5em);
    text-align: center;
}
#inputfield {
    overflow: hidden;
    padding-top: 5px;
    padding-bottom: 5px;
    margin-top: 50px;
    margin-bottom: 10px;
}
::placeholder {
    color: #E7E6E6;
    opacity: 0.8;
}
#name {
    height: 35px;
    width: 813px;
    outline: none;
    background-color: #001F5F;
    color: #E7E6E6;
    text-align: left;
    vertical-align: middle;
    font-size: 22px;
    box-shadow: 1px 2px 4px 2px darkgray;
    margin-right: 10px;
    border: 5px;
    border-color: #E7E6E6;
    float: left;
    border-radius: 5px 5px 5px 5px;
}
#add {
    height: 35px;
    width: 35px;
    background-color: #E7E6E6;
    color: #001F5F;
    font-size: 32px;
    font-style: bold;
    text-align: center;
    vertical-align: middle;
    line-height: 35px;
    cursor: pointer;
    box-shadow: 1px 2px 4px 2px darkgray;
    float: left;
    border-radius: 5px 5px 5px 5px;
}
#add:hover {
    background-color:#001F5F;
    color: #E7E6E6;
}
#background {
    box-shadow: 0px 2px 4px 2px darkgray;
    width: 900px;
    height: 0px;
    background-color: #E7E6E6;
    padding-top: 20px;
    border-radius: 5px 5px 5px 5px;
}
.start, .end {
    text-align: center;
    margin-top: 250px;
    font-size: 32px;
    padding: 0px;
    vertical-align: middle;
}
#spacer {
    width: 10px;
    height: 35px;
    background-color:#E7E6E6;
}
.input {
    height: 35px;
    width: 808px;
    background-color:#001F5F;
    padding-left: 5px;
    border: 0px;
    font-size: 22px;
    color: #E7E6E6;
    text-align: left;
    vertical-align: middle;
    outline: none;
    box-shadow: 0px 2px 4px 2px darkgray;
    border-radius: 5px 5px 5px 5px;
}
.bin {
    width: 35px;
    height: 35px;
    font-size: 24px;
    font-style: normal;
    background-color: #E7E6E6;
    color:#001F5F;
    text-align: center;
    vertical-align: middle;
    line-height: 35px;
    cursor: pointer;
    border-radius: 5px 5px 5px 5px;
}
.bin:hover {
    background-color:#001F5F;
    color: #E7E6E6;
    box-shadow: 0px 2px 4px 2px darkgray;
}
.item {
    margin-left: 32px;
    display: table;
    table-layout: fixed;
    width: 858px;
    margin-bottom: 20px;
}
.column {
    display: table-cell;
}
.thelist {
    margin-left: calc(50% - 450px);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Oliver's To-Do List</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<h1 id="title">Oliver's To-Do List</h1>
<body>
<div class="thelist">
    <div id="inputfield">
    <input type="text" placeholder="Start typing here..."id="name">
    <div id="add">+</div>
    </div>
    <div id="background">
    </div>
</div>
<script src="main.js"></script>
</body>
</html>

Спасибо!

Ответы [ 3 ]

0 голосов
/ 25 апреля 2020

О, ты решил это. Я только что попробовал и изменил что-то в индексе. html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Oliver's To-Do List</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<h1 id="title">Oliver's To-Do List</h1>
<body>
<div class="thelist">
    <div id="inputfield">
    <input type="text" placeholder="Start typing here..."id="name">
    <div id="add" onclick="addevent()">+</div>
    </div>
    <div id="background">
    </div>
</div>
<script src="main.js"></script>
</body>
</html>

Я добавил onclick = "addevent ()", и он работает

0 голосов
/ 25 апреля 2020
getAdd.addEventListener("click", addevent(), false);

должно быть

getAdd.addEventListener("click", addevent, false);

Согласно этому примеру из https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener:

// Function to change the content of t2
function modifyText() {
  const t2 = document.getElementById("t2");
  if (t2.firstChild.nodeValue == "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
  }
}

// Add event listener to table
const el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);
0 голосов
/ 25 апреля 2020

Хорошо, поэтому я обнаружил, что в приемнике событий getAdd проблема заключалась в паре скобок после имени функции; как только они будут удалены, это будет работать просто отлично!

Если кто-то из читателей хочет добавить к этому свои знания, опыт и опыт или предложить какие-либо другие улучшения, пожалуйста, сделайте!

Спасибо!

...