css 如何使用JavaScript获取被点击的元素

mbzjlibv  于 2023-06-25  发布在  Java
关注(0)|答案(2)|浏览(154)

首先,我想指出的是,我看到有关于跟踪事件侦听器的类似帖子,但在我的情况下,我只是无法弄清楚。我很熟悉event.target属性,但在我的情况下,我只是不能使它。
这是我的代码片段:

const taskListSection = document.querySelector('.task-list-section');
const taskListAddModal = document.querySelector('.task-list-add-modal');
const confirmTaskAddBtn = document.getElementById('add-list');
const cancelTaskAddBtn = document.getElementById('cancel-add-list');
const addTaskBtn = document.getElementById('add-task');
const titleInput = document.getElementById('title');
const descriptionInput = document.getElementById('description');
const timeInput = document.getElementById('time');

const clearUserInput = () => {
    titleInput.value = '';
    descriptionInput.value = '';
    timeInput.value = '';
};

const taskListAddModalHandler = () => {
    const taskList = taskListSection.querySelectorAll('li');
    taskListAddModal.classList.toggle('visible');
    addTaskBtn.classList.toggle('visible');
    taskList.forEach((list) => {
        list.classList.toggle('visible');
    });
    clearUserInput();
};
const confirmAddTask = () => {
    const newTask = document.createElement('li');
    const taskList = taskListSection.querySelectorAll('li');
    const titleInputValue = titleInput.value;
    const descriptionInputValue = descriptionInput.value;
    const timeInputValue = timeInput.value;
    
    if(titleInputValue.trim() === ''){
        alert('Please enter a title of your task!');
        return;
    }

    newTask.className = 'visible';
    newTask.innerHTML = 
    `<button  class="check-task">C</button>
    <button  class="remove-task">X</button>
    <h4>Title:</h4>
    <p>${titleInputValue}</p>
    <h4>Description:</h4>
    <p>${descriptionInputValue}</p>
    <h4>Time:</h4>
    <p>${timeInputValue}</p>`;

    taskListSection.append(newTask);
    taskListAddModal.classList.remove('visible');
    taskList.forEach((list) => {
        list.classList.add('visible');
    });
    addTaskBtn.classList.toggle('visible');
    clearUserInput();
};

addTaskBtn.addEventListener('click', taskListAddModalHandler);
cancelTaskAddBtn.addEventListener('click', taskListAddModalHandler);
confirmTaskAddBtn.addEventListener('click', confirmAddTask);
body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.main-wrapper{
    width: 70rem;
    margin: 0 auto;
    border: 2px solid black;
    position: relative;
}
.main-wrapper #add-task{
    display: none;
}
.main-wrapper #add-task.visible{
    position: absolute;
    top: 150px;
    right: 100px;
    width: 50px;
    height: 50px;
    font-size: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
}
ul{
    border: 1px solid black;
    width: 40rem;
    height: 40rem;
    margin: 10rem auto;
    padding: 0;
    background-color: red;
    overflow-x: scroll;
}
ul form{
    
    flex-direction: column;
    width: 100%;
    height: 40rem;
    background-color: white;
    display: none;
}
ul form input[type=button]{
    display: block;
    margin: 10px auto;
}
ul form.visible{
    display: flex;
}
ul li{
    display: none;
}
ul li.visible{
    display: block;
    width: 80%;
    list-style: none;
    border: 2px solid black;
    margin: 10px;
    position: relative;
}
ul li .check-task{
    position: absolute;
    width: 30px;
    height: 30px;
    top: 30px;
    right: 30px;
}
ul li .remove-task{
    position: absolute;
    width: 30px;
    height: 30px;
    bottom: 30px;
    right: 30px;
}
ul li.checked{
    background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <section class="main-wrapper">
        <button id="add-task" class="visible">+</button>
        <ul class="task-list-section">
            <form class="task-list-add-modal">
                <label for="title">Title:</label>
                <input type="text" id="title">
                <label for="description">Description:</label>
                <textarea type="text" id="description" maxlength="100"></textarea>
                <label for="time">Time:</label>
                <input type="text" id="time">
                <div class="to-do-list-confirmation">
                    <input type="button" id="add-list" value="ADD">
                    <input type="button" id="cancel-add-list" value="CANCEL">
                </div>  
            </form>
        </ul>
    </section>
    <script src="app.js"></script>
</body>
</html>

我有一个问题,跟踪哪个按钮'C'上的'li'元素被点击。因此,这背后的逻辑是,当我在某个li元素上单击“C”按钮时,我希望THAT“li”元素获得名为“checked”的类(类“checked”将为“li”元素提供绿色背景)。您可以通过单击右上角的“+”按钮来创建“li”元素,然后单击“添加”按钮来填充输入元素。对不起,糟糕的设计,我做了它真的很快,只是试图解释什么是我的问题。我希望你给予我的解决方案使用纯JS。先谢谢你了。

vkc1a9a2

vkc1a9a21#

既然你要求一个例子,下面的例子被简化,以显示如何在你的处理函数中使用一个事件参数,用于你的监听器中被触发的元素。这是为了向你展示它是如何被简化的。您需要将此功能应用到您的代码中,一旦您理解了这个概念,它就相当容易了。
在下面的代码片段中进一步说明...

// here I am querying all the buttons in the dom
let el = document.querySelectorAll("button");

// I am running them through a loop and applying an event listner with a handler function on click
for(let i = 0; i < el.length; i++){
  el[i].addEventListener('click', handler);
}

// the function passes a parameter "event" => e. 
// we use the e.target to get the element being pressed
// I use a data attribute in the element being pressed 
// to locate an id and affect its background color
function handler(e){
  let handler = e.target.getAttribute("data-handler");
  let target = document.getElementById(handler);
  target.style.backgroundColor = '#d4d4d4';
}
<div id="one">Div One</div>
<div id="two">Div Two</div>
<div id="three">Div Three</div>
<div id="four">Div Four</div>

<button data-handler="one">This btn handles div one</button>
<button data-handler="two">This btn handles div two</button>
<button data-handler="three">This btn handles div three</button>
<button data-handler="four">This btn handles div four</button>
wgeznvg7

wgeznvg72#

是的,我的问题是,我的'li'元素不是预制的,可以这么说,就像在你的例子。它们是用JS创建的,所以我不知道如何“连接”按钮和他的li元素,然后使用target属性(就像你使用data-handler和div元素的id一样)。但是我找到了一种方法,通过使用Math.random给li元素随机ID,然后我用这个数字作为按钮上的数据处理器值,然后休息就很容易了。非常感谢你给了我一个小小的推动,所以我做到了。它的工作原理.这里是一个代码片段可能对某人有用.

const taskListSection = document.querySelector('.task-list-section');
const taskListAddModal = document.querySelector('.task-list-add-modal');
const confirmTaskAddBtn = document.getElementById('add-list');
const cancelTaskAddBtn = document.getElementById('cancel-add-list');
const addTaskBtn = document.getElementById('add-task');
const titleInput = document.getElementById('title');
const descriptionInput = document.getElementById('description');
const timeInput = document.getElementById('time');

const clearUserInput = () => {
    titleInput.value = '';
    descriptionInput.value = '';
    timeInput.value = '';
};

const taskListAddModalHandler = () => {
    const taskList = taskListSection.querySelectorAll('li');
    taskListAddModal.classList.toggle('visible');
    addTaskBtn.classList.toggle('visible');
    taskList.forEach((list) => {
        list.classList.toggle('visible');
    });
    clearUserInput();
};
const confirmAddTask = () => {
    const newTask = document.createElement('li');
    const taskList = taskListSection.querySelectorAll('li');
    const titleInputValue = titleInput.value;
    const descriptionInputValue = descriptionInput.value;
    const timeInputValue = timeInput.value;
    
    if(titleInputValue.trim() === ''){
        alert('Please enter a title of your task!');
        return;
    }

    newTask.className = 'visible';
    let newTaskId = newTask.id = Math.random().toString();
    newTask.innerHTML = 
    `<button data-handler = '${newTaskId}'  class="check-task">C</button>
    <button data-handler = '${newTaskId}' class="remove-task">X</button>
    <h4>Title:</h4>
    <p>${titleInputValue}</p>
    <h4>Description:</h4>
    <p>${descriptionInputValue}</p>
    <h4>Time:</h4>
    <p>${timeInputValue}</p>`;

    taskListSection.append(newTask);
    taskListAddModal.classList.remove('visible');
    taskList.forEach((list) => {
        list.classList.add('visible');
    });
    const checkTaskBtn = document.querySelectorAll('.check-task');
    for(const btn of checkTaskBtn){
        btn.addEventListener('click', taskCheck);
    }
    addTaskBtn.classList.toggle('visible');
    clearUserInput();
};

const taskCheck = (e) => {
    let handler = e.target.getAttribute("data-handler");
    let target = document.getElementById(handler);
    target.classList.toggle('checked');
}

addTaskBtn.addEventListener('click', taskListAddModalHandler);
cancelTaskAddBtn.addEventListener('click', taskListAddModalHandler);
confirmTaskAddBtn.addEventListener('click', confirmAddTask);
body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.main-wrapper{
    width: 70rem;
    margin: 0 auto;
    border: 2px solid black;
    position: relative;
}
.main-wrapper #add-task{
    display: none;
}
.main-wrapper #add-task.visible{
    position: absolute;
    top: 150px;
    right: 100px;
    width: 50px;
    height: 50px;
    font-size: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
}
ul{
    border: 1px solid black;
    width: 40rem;
    height: 40rem;
    margin: 10rem auto;
    padding: 0;
    background-color: red;
    overflow-x: scroll;
}
ul form{
    
    flex-direction: column;
    width: 100%;
    height: 40rem;
    background-color: white;
    display: none;
}
ul form input[type=button]{
    display: block;
    margin: 10px auto;
}
ul form.visible{
    display: flex;
}
ul li{
    display: none;
}
ul li.visible{
    display: block;
    width: 80%;
    list-style: none;
    border: 2px solid black;
    margin: 10px;
    position: relative;
}
ul li .check-task{
    position: absolute;
    width: 30px;
    height: 30px;
    top: 30px;
    right: 30px;
}
ul li .remove-task{
    position: absolute;
    width: 30px;
    height: 30px;
    bottom: 30px;
    right: 30px;
}
ul li.checked{
    background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <section class="main-wrapper">
        <button id="add-task" class="visible">+</button>
        <ul class="task-list-section">
            <form class="task-list-add-modal">
                <label for="title">Title:</label>
                <input type="text" id="title">
                <label for="description">Description:</label>
                <textarea type="text" id="description" maxlength="100"></textarea>
                <label for="time">Time:</label>
                <input type="text" id="time">
                <div class="to-do-list-confirmation">
                    <input type="button" id="add-list" value="ADD">
                    <input type="button" id="cancel-add-list" value="CANCEL">
                </div>  
            </form>
        </ul>
    </section>
    <script src="app.js"></script>
</body>
</html>

相关问题