在我的情况下,如何获取使用 java 脚本单击的元素

如何解决在我的情况下,如何获取使用 java 脚本单击的元素

首先我想指出的是,我看到有关于跟踪事件侦听器的类似帖子,但就我而言,我就是想不通。我熟悉 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>

我无法跟踪点击了哪个“li”元素上的哪个按钮“C”。所以这背后的逻辑是,当我点击某个创建的 li 元素上的“C”按钮时,我想要 THAT 'li' 元素来获取名为 'checked' 的类(类 'checked' 将为该“li”元素提供绿色背景)。您可以通过单击右上角的“+”按钮而不是填充输入元素然后单击添加按钮来创建“li”元素。抱歉糟糕的设计,我让它变得非常快,只是为了尝试解释我的问题是什么。我希望你给我使用纯 JS 的解决方案。提前致谢。

解决方法

由于您要求提供示例,因此下面的示例已简化,以展示如何在处理程序函数中使用事件参数,以便在侦听器中触发的元素上使用。这是过度简化以向您展示它是如何完成的。您需要将此功能应用到您的代码中,一旦您理解了这个概念,这将变得相当容易。

在下面的代码片段中进一步说明...

// 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>

,

是的,我的问题是我的“li”元素不是预先制作的,就像你的例子一样。它们是用 JS 创建的,所以我无法弄清楚如何“连接”按钮和他的 li 元素,然后使用目标属性(就像你对数据处理程序和 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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res