javascript 仅将输入值更新到元素JS

g0czyy6m  于 2023-06-04  发布在  Java
关注(0)|答案(3)|浏览(145)

我已经创建了一个索引文件,以便将在此处输入的信息添加到创建的元素中(这是用于审查部分的index.html文件在此处),其中包括CSS和js

let name = document.querySelector('.name').value;
    let message = document.querySelector('.message').value;
    let btn = document.getElementById('button');
    let div = document.querySelector('.items')

    btn.addEventListener('click', ()=>{
        let item = document.createElement('div')
        let inner = `
                <h3>${name}</h3>
                <p>${message}</p>
                `
        item.className = "message-item"        
        item.innerHTML = inner        
        div.append(item)
    });
html, body{
            padding: 0;
            margin: 0;
        }
        .msg{
            padding: 2em;
            margin: 2em;
            border-radius: 2vh;
            height: 70vh;
            display: flex;
            align-items: center;
            justify-content: left;
            flex-direction: column;
            background-color: #1e90ff;
        }
        .items{
            height: 65vh;
            overflow: scroll;
            color: white;
            width: 100%;
            overflow-x: hidden;
            margin: 10px;
        }
        input{
            padding: 10px;
            border: none;
            border-radius: 8px;
            outline: none;
            font-size: 1em;
        }
        #button{
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            font-size: 1em;
        }
        .button{
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            font-size: 1em;
        }
        .message-item{
            background-color: black;
            padding: 1em;
            border-radius: 8px;
            margin: 3px;
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>

</head>
<body>
    <div class="msg">
        <div class="items"></div>
        <div class="input">
                <input type="text" class="name" placeholder="Name">
                <input type="text" class="message" placeholder="Message">
                <button id="button">Submit</button>
                <button type="reset">Reset</button>
        </div>
    </div>
</body>

</html>

因此,我希望它追加具有不同值的元素,例如,一旦我输入name“harry”和message作为“this is the message”,然后我重置并输入另一个namemessage,则新创建的元素应显示新输入的namemessage

pgpifvop

pgpifvop1#

name变量应该是指向元素的指针,而不是指向值的指针。
此外,您应该在添加后清除输入。

const
  name = document.querySelector('.name'),
  message = document.querySelector('.message'),
  btn = document.getElementById('button'),
  div = document.querySelector('.items');

const handleAdd = (e) => {
  div.insertAdjacentHTML('beforeend', `
    <div class="message-item">
      <h3>${name.value}</h3>
      <p>${message.value}</p>
    </div>
  `);
  name.value = '';    // Clear name
  message.value = ''; // Clear message
};

btn.addEventListener('click', handleAdd);
html,
body {
  padding: 0;
  margin: 0;
}

.msg {
  padding: 2em;
  margin: 2em;
  border-radius: 2vh;
  height: 70vh;
  display: flex;
  align-items: center;
  justify-content: left;
  flex-direction: column;
  background-color: #1e90ff;
}

.items {
  height: 65vh;
  overflow: scroll;
  color: white;
  width: 100%;
  overflow-x: hidden;
  margin: 10px;
}

input {
  padding: 10px;
  border: none;
  border-radius: 8px;
  outline: none;
  font-size: 1em;
}

#button {
  padding: 10px 20px;
  border-radius: 8px;
  border: none;
  font-size: 1em;
}

.button {
  padding: 10px 20px;
  border-radius: 8px;
  border: none;
  font-size: 1em;
}

.message-item {
  background-color: black;
  padding: 1em;
  border-radius: 8px;
  margin: 3px;
}
<div class="msg">
  <div class="items"></div>
  <div class="input">
    <input type="text" class="name" placeholder="Name">
    <input type="text" class="message" placeholder="Message">
    <button id="button">Submit</button>
    <button type="reset">Reset</button>
  </div>
</div>

更好的方法

一个更好的例子是使用表单。这样,您就可以利用内置的表单验证、提交和重置功能。
例如,您可以通过元素的名称调用元素,并且您还可以获得Enter键支持的额外好处。
1.输入名称
1.按Tab键
1.请输入留言
1.按Enter键
1.项目已添加
1.表单已清除
1.焦点发送到名称

const handleAdd = (e) => {
  e.preventDefault(); // Prevent page from navigating
  const
    form = e.target,
    formElements = form.elements,
    parent = form.closest('.msg'),
    items = parent.querySelector('.items');
  items.insertAdjacentHTML('beforeend', `
    <div class="message-item">
      <h3>${formElements.name.value}</h3>
      <p>${formElements.message.value}</p>
    </div>
  `);
  formElements.name.value = '';    // Clear name
  formElements.message.value = ''; // Clear message
  formElements.name.focus();
};

document.forms.namedItem('new-msg')
  .addEventListener('submit', handleAdd);
html,
body {
  padding: 0;
  margin: 0;
}

.msg {
  padding: 2em;
  margin: 2em;
  border-radius: 2vh;
  height: 70vh;
  display: flex;
  align-items: center;
  justify-content: left;
  flex-direction: column;
  background-color: #1e90ff;
}

.items {
  height: 65vh;
  overflow: scroll;
  color: white;
  width: 100%;
  overflow-x: hidden;
  margin: 10px;
}

input {
  padding: 10px;
  border: none;
  border-radius: 8px;
  outline: none;
  font-size: 1em;
}

.form-btn {
  padding: 10px 20px;
  border-radius: 8px;
  border: none;
  font-size: 1em;
}

.message-item {
  background-color: black;
  padding: 1em;
  border-radius: 8px;
  margin: 3px;
}
<div class="msg">
  <div class="items"></div>
  <form id="new-msg" autocomplete="off">
    <input type="text" name="name" placeholder="Name" required>
    <input type="text" name="message" placeholder="Message">
    <button type="submit" class="form-btn">Submit</button>
    <button type="reset" class="form-btn">Reset</button>
  </form>
</div>

本地存储

这是一个本地存储的例子。这里的主要思想是如何存储和恢复消息的状态。

const MESSAGES_KEY = "messages";

const main = () => {
  // Restore all messages
  const messageContainer = document.querySelector(".items");
  __retrieveAllMessages().forEach((message) => {
    insertMessage(message, messageContainer);
  });
  // Add event listener
  document.forms.namedItem("new-msg").addEventListener("submit", handleAdd);
};

const saveMessage = (message) => {
  __saveAllMessages(__retrieveAllMessages().concat(message));
};

const insertMessage = (message, container) => {
  container.insertAdjacentHTML("beforeend", messageToHtml(message));
};

const messageToHtml = ({ name, message }) => `
  <div class="message-item">
    <h3>${name}</h3>
    <p>${message}</p>
  </div>
`;

const handleAdd = (e) => {
  e.preventDefault(); // Prevent page from navigating
  const form = e.target,
    message = {
      name: form.elements.name.value,
      message: form.elements.message.value,
    };
  saveMessage(message);
  insertMessage(message, form.closest(".msg").querySelector(".items"));
  form.elements.name.value = ""; // Clear name
  form.elements.message.value = ""; // Clear message
  form.elements.name.focus();
};

const __retrieveAllMessages = () => {
  return JSON.parse(localStorage.getItem(MESSAGES_KEY) ?? "[]");
};

const __saveAllMessages = (messages = []) => {
  return localStorage.setItem(MESSAGES_KEY, JSON.stringify(messages));
};

main();
nvbavucw

nvbavucw2#

你需要在每次按下提交按钮时得到你输入的值,而不是在页面加载时得到一次,而且你还需要在按下重置按钮时清除你的输入

let btn = document.getElementById('button');
let reset = document.getElementById('reset');
let div = document.querySelector('.items')

btn.addEventListener('click', () => {
  let name = document.querySelector('.name').value;
  let message = document.querySelector('.message').value;
  let item = document.createElement('div')
  let inner = `
                <h3>${name}</h3>
                <p>${message}</p>
                `
  item.className = "message-item"
  item.innerHTML = inner;
  div.append(item)
});

reset.addEventListener('click', () => {
  let name = document.querySelector('.name').value = '';
  let message = document.querySelector('.message').value = '';
});
html, body{
            padding: 0;
            margin: 0;
        }
        .msg{
            padding: 2em;
            margin: 2em;
            border-radius: 2vh;
            height: 70vh;
            display: flex;
            align-items: center;
            justify-content: left;
            flex-direction: column;
            background-color: #1e90ff;
            color: white;
        }
        .items{
            height: 65vh;
            overflow: scroll;
            color: white;
            width: 100%;
            overflow-x: hidden;
            margin: 10px;
        }
        input{
            padding: 10px;
            border: none;
            border-radius: 8px;
            outline: none;
            font-size: 1em;
        }
        #button{
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            font-size: 1em;
        }
        .button{
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            font-size: 1em;
        }
        .message-item{
            background-color: black;
            padding: 1em;
            border-radius: 8px;
            margin: 3px;
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
    <div class="msg">
        <div class="items"></div>
        <div class="input">
                <input type="text" class="name" placeholder="Name">
                <input type="text" class="message" placeholder="Message">
                <button id="button">Submit</button>
                <button id="reset">Reset</button>
        </div>
    </div>
</body>

</html>
deyfvvtc

deyfvvtc3#

在输入被填充之前,您可以从输入中获取值。它们只是字符串值,在输入更改时不会动态更新。
我将这些行移到了函数内部,这样每次单击按钮时都可以获得最新的数据。

let btn = document.getElementById('button');
btn.addEventListener('click', ()=>{
    let name = document.querySelector('.name').value;
    let message = document.querySelector('.message').value;
    let div = document.querySelector('.items')
    
    let item = document.createElement('div')
    let inner = `
            <h3>${name}</h3>
            <p>${message}</p>
            `
    item.className = "message-item"        
    item.innerHTML = inner        
    div.append(item)
});
html, body{
            padding: 0;
            margin: 0;
        }
        .msg{
            padding: 2em;
            margin: 2em;
            border-radius: 2vh;
            height: 70vh;
            display: flex;
            align-items: center;
            justify-content: left;
            flex-direction: column;
            background-color: #1e90ff;
        }
        .items{
            height: 65vh;
            overflow: scroll;
            color: white;
            width: 100%;
            overflow-x: hidden;
            margin: 10px;
        }
        input{
            padding: 10px;
            border: none;
            border-radius: 8px;
            outline: none;
            font-size: 1em;
        }
        #button{
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            font-size: 1em;
        }
        .button{
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            font-size: 1em;
        }
        .message-item{
            background-color: black;
            padding: 1em;
            border-radius: 8px;
            margin: 3px;
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>

</head>
<body>
    <div class="msg">
        <div class="items"></div>
        <div class="input">
                <input type="text" class="name" placeholder="Name">
                <input type="text" class="message" placeholder="Message">
                <button id="button">Submit</button>
                <button type="reset">Reset</button>
        </div>
    </div>
</body>

</html>

相关问题