用于添加和删除元素的 Onclick 事件

我正在尝试创建一个可以多次添加和删除元素的 onclick 事件。我已经考虑过使用setproperty和更改visibility(以及:after伪类),但它需要更改,这会position破坏文档中的很多内容。到目前为止,我只能想出添加元素一次,然后删除元素一次的方法。有没有办法让这种情况发生多次(每次单击该元素时)?



// Create New Element

let html = document.createElement('p');

html.className = 'skills';

html.id = 'html-skills';

html.setAttribute('title', 'HTML5 Proficiency');

html.appendChild(document.createTextNode('5%'));

html.style.setProperty('font-size', '16px')

// Grab Old Element

const oldHTML = document.getElementById('html');

// On Click function to add element

oldHTML.addEventListener('click', onClick);

function onClick(e) {

    document.getElementById('htmlJS').appendChild(html)

}

// On click function to remove element

const htmlJS = document.getElementById('htmlJS')

html.addEventListener('click', removeHTML);

function removeHTML(e) {

    let newHTML = document.getElementById("htmlJS");

    let htmlNested = document.getElementById("htmlJS").lastChild;

   

    htmlNested.lastChild.remove();

}

 <script

      src="https://kit.fontawesome.com/d3d2bbf2ae.js"

      crossorigin="anonymous"

 ></script>

 

 <div class="skills-list__1 skills-icons" id="skills1">

  <i class="fab fa-html5 html" id="html" title="HTML5"><div id="htmlJS"></div></i>

 </div>


慕姐4208626
浏览 122回答 1
1回答

慕盖茨4494581

您无法重用 onClick 函数(制作“5%”html)的原因是您已经用removeHTML 函数覆盖了该函数。我使用一个事件函数来写入和删除内部 html 文本。有很多方法可以实现你想要的。希望你尝试自己的方式。// Create New Elementlet html = document.createElement('p');html.className = 'skills';html.id = 'html-skills';html.setAttribute('title', 'HTML5 Proficiency');html.appendChild(document.createTextNode(''));html.style.setProperty('font-size', '16px')document.getElementById('htmlJS').appendChild(html)// Grab Old Elementconst oldHTML = document.getElementById('html');// On Click function to add elementoldHTML.addEventListener('click', onClick);function onClick(e) {if (html.innerHTML === '') {&nbsp; html.innerHTML = '5%'&nbsp; } else {&nbsp; html.innerHTML = ''&nbsp; }}// On click function to remove element//Whatever you named this htmlJS id it still has onCLick function.const htmlJS = document.getElementById('htmlJS')html.addEventListener('click', removeHTML);function removeHTML(e) {&nbsp; &nbsp; let newHTML = document.getElementById("htmlJS");&nbsp; &nbsp; let htmlNested = document.getElementById("htmlJS").lastChild;&nbsp; &nbsp;}&nbsp;<script&nbsp; &nbsp; &nbsp; src="https://kit.fontawesome.com/d3d2bbf2ae.js"&nbsp; &nbsp; &nbsp; crossorigin="anonymous"&nbsp;></script>&nbsp;&nbsp;<div class="skills-list__1 skills-icons" id="skills1">&nbsp; <i class="fab fa-html5 html" id="html" title="HTML5"><div id="htmlJS"></div></i>&nbsp;</div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript