【问题标题】:Add a click event function to a button which creates a new paragraph in box layout when onclicks on it向按钮添加点击事件函数,当点击它时,它会在框布局中创建一个新段落
【发布时间】:2021-07-31 10:45:50
【问题描述】:

我一直在尝试按照我描述的方式创建此点击事件,但我不断收到提示消息,而不是按钮下方提供的框布局内的段落。

【问题讨论】:

  • 你能添加你的代码吗
  • 常量 btn=document.getElementById("btn");常量段落=document.getElementById("段落"); btn.addEventListener("click", function() { paragraph.textContent="some text"});
  • 常量 btn=document.getElementById("btn");常量段落=document.getElementById("段落"); btn.addEventListener("click", function() { paragraph.textContent="some text"});

标签: javascript dom-events dom-manipulation


【解决方案1】:

为盒子添加一个 div。为要添加的段落添加输入文本区域。还有一个按钮来实际添加你的段落。

const btn = document.getElementById("btn"); 
  const clr = document.getElementById("clr"); 
  const paragraph = document.getElementById("paragraph"); 
  const will_add = document.getElementById("will_add"); 
  var the_paragraph = "";

  btn.addEventListener("click", function() { 

    the_paragraph = the_paragraph + will_add.value; 
    paragraph.innerHTML = the_paragraph; 
  });

  clr.addEventListener("click", function() { 
    will_add.value = "";
    the_paragraph = ""; 
    paragraph.innerHTML = ""; 
  });
.box {
  height: 200px;
  width: 400px;
  border: 1px solid red;
  border-radius: 4px;
}

textarea {
  height: 50px;
  width: 400px;
}
<div class="box">
  <p id="paragraph"></p>
</div>

<textarea id="will_add" type="textarea" placeholder="Add your paragraph here..."></textarea>
<br/>
<button id="btn">Add</button>
<button id="clr">Clear</button>

【讨论】:

    猜你喜欢
    • 2014-12-28
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    相关资源
    最近更新 更多