javascript - addEventListener:点击移除标签

标签 javascript html dom onclick addeventlistener

以下是我想获得帮助的案例的详细信息:

    <section class='result'> </section>
some tags... when the input value found/not found

我创建一个输入来查找一些文本/文章,如果找不到输入值,它将显示:

sorry can't found input same value on box searching

然后我尝试再次单击按钮,当我多次单击 button 时,它会一次又一次地重复该文本...

sorry can't found 'input same value on box searching'
sorry can't found 'input same value on box searching'
sorry can't found 'input same value on box searching'
sorry can't found 'input same value on box searching'
sorry can't found 'input same value on box searching'

等等...

我只想让它显示一次,当输入改变时,它不会再次重复,它会显示新的不同值:抱歉不能... 'new input value'>/p>

也就是当输入数据找不到的时候,当输入数据找到的时候,我在搜索框中更改输入数据后,我想删除那个文本sorry cant....

然后在找到之后显示文章数据...

所以我想得到一些帮助,如何不重复它们,然后在找到 DOM 输入的数据后插入新标签。

代码如下: https://jsfiddle.net/cornloh/d2Lgkpxe/

const find = el => document.querySelector(el)
const create = el => document.createElement(el)

const lookingThem = find('.searchButton').addEventListener('click', (e) => {
  e.preventDefault()
  const inputText = find('.box').value.trim(); 
  // console.log(inputText.length);
  result(inputText);
})

const result = searching => {
  const wikipedia = `https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=20&srsearch=${searching}`; // API
  fetch(wikipedia)
    .then(resolve => resolve.json())
    .then(data => {
      if(typeof data.continue === 'undefined'){
        displayCantFound(find('.box').value)
      } else {
        console.log(data);
      }
    })
    .catch((e) => alert('an error occurred', e))
}

const displayCantFound = theInputValue => {
  find('.result').insertAdjacentHTML('beforeend',
  `<div>
      <h3> sorry can't found what you are looking ${theInputValue} </h3>
  </div>`)
}

// const displayError = () => {
//
// }

最佳答案

不要每次都插入新的 html。只是完全取代它。

const displayCantFound = theInputValue => {
  find('.result').innerHTML  = `<div>
      <h3> sorry can't found what you are looking ${theInputValue} </h3>
  </div>`
}

如果你想在找到数据时消除错误,你可以将以下部分代码替换为我的代码

if(typeof data.continue === 'undefined'){
   displayCantFound(find('.box').value)
} else {
   console.log(data);
   //this line is added
   document.querySelector('.result').innerHTML = '';
}

关于javascript - addEventListener:点击移除标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54491652/

相关文章:

javascript - 我无法将数据从 Controller 传递到 Sencha Touch 2.4 中的 View

Javascript - 从标签中获取时间

javascript - flash视频播放器如何变成全屏

javascript - 获取 "object HTMLInputElement"的值和函数错误

javascript - 为什么在 JavaScript 中为实例变量声明原型(prototype)属性

Javascript Setter 没有设置额外的属性值

jquery - 编程选择后 div 内容的大小不一致

javascript - jQuery/Javascript 无法访问有关元素的信息

javascript - Meteor JS 在没有模板的情况下首先加载 : gives "null" error

html - JSP内容一目了然