【问题标题】:How do I get the values of an appended element in JavaScript?如何在 JavaScript 中获取附加元素的值?
【发布时间】:2021-01-28 00:56:10
【问题描述】:

我正在创建一个需要多个时间输入的计算器,我需要获取已添加的已创建 div 元素的值。

这是附加元素的代码

let div - document.createElement("div"); 
div.innerHTML = html; 
schedule.appendChild(div.firstElementChild); 

这是正在创建的 html 元素的代码:

<div class = "times"> 
 <input id = "start" type = "time" value = ""> 
 <input id = "end" type = "time"  value = ""> 
</div> 

我需要在 JavaScript 中获取由 JavaScript 代码创建的时间输入的值。我该怎么做?

【问题讨论】:

  • 获取任何其他元素值的方式相同。 document.getElementById("start").value
  • 因此,document.getElementById("start").value 获取 ID 为“start”的输入的值。我已经这样做了。我需要从 html 代码创建并附加到文档的元素的 div 的值,所以很遗憾您的评论不是很有帮助。
  • div 没有值,只有输入值。
  • 您可以将div.firstElementChild保存在一个变量中,然后使用thatVariable.value
  • 我试图从一个非常不完整的描述中了解你真正想要什么。

标签: javascript


【解决方案1】:

我想我理解的和你需要的是下面的代码。 . .检查出来,让我知道你的想法。 . .. 当您选择时间时,将触发 onchange 事件,并且该值将作为“

”标签附加到它的父 div。如果您愿意,您也可以将值附加到正文。 . .

let div1 = document.createElement("div"); 
const html1=`
<div class = "times" style='border:1px solid red;width:300px;height:100px;padding:10px;margin:5px;'> 
 <input onchange='change(this)' type = "time" value = "" /> 
 <input onchange='change(this)' type = "time"  value = "" /> 
</div> 
`;
div1.innerHTML = html1; 
let div2 = document.createElement("div"); 
const html2=`
<div class = "times" style='border:1px solid red;width:300px;height:100px;padding:10px;margin:5px;'> 
 <input onchange='change(this)' type = "time" value = "" /> 
 <input onchange='change(this)' type = "time"  value = "" /> 
</div> 
`;
div2.innerHTML = html2; 
let schedule=document.getElementById("schedule");
schedule.appendChild(div1); 
schedule.appendChild(div2); 

function change(e){
    let par=e.parentNode;
    let p=document.createElement('p');
    p.innerHTML=`${e.value}`;
    par.appendChild(p);
}
<div id="schedule" style="border:1px solid blue;width:500px;height:300px;padding:20px;">
 shedule div
</div>

【讨论】:

  • 所以,我正在自学 JavaScript,我不明白这段代码中的大部分内容,你能否解释一下每个代码部分的作用,以便我看看这是否是什么我在问?我知道解释代码需要一些努力。我真的只是想学习 JS 并想深入了解该语言。提前谢谢你。
  • 另外,为什么里面有 CSS 代码?我不需要 CSS 代码。边框不是我想要的盒子样式。
猜你喜欢
  • 2016-08-22
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 2011-12-11
  • 2011-02-09
  • 2012-08-18
  • 1970-01-01
  • 2016-11-06
相关资源
最近更新 更多