未使用Javascript功能删除芯片标签

问题描述 投票:0回答:2

我正在尝试使用单词作为标记来创建输入,然后允许用户删除它们。每次单击X时,我都会收到一条错误消息,说

ReferenceError:未定义删除

我不确定我在做什么错。我正在使用以下代码:

HTML:

<div class="ingredients">
  <ul id="list"></ul>
  <input type="text" id="ingredients" placeholder="type and Enter ...">
</div>

Javascript

var txt = document.getElementById('ingredients');
var list = document.getElementById('list');
var items = ['PHP', 'React.js', 'WordPress'];

txt.addEventListener('keypress', function(e) {
  if (e.key === 'Enter') {
    let val = txt.value;
    if (val !== '') {
      if (items.indexOf(val) >= 0) {
        alert('Tag name is a duplicate');
      } else {
        items.push(val);
        render();
        txt.value = '';
        txt.focus();
      }
    } else {
      alert('Please type a tag Name');
    }
  }
});

function render() {
  list.innerHTML = '';
  items.map((item, index) => {
    list.innerHTML += `<li><span>${item}</span><a href="javascript: remove(${index})">X</a></li>`;
  });
}

function remove(i) {
  items = items.filter(item => items.indexOf(item) != i);
  render();
}

window.onload = function() {
  render();
  txt.focus();
}
javascript html tags
2个回答
1
投票

它看起来像订购问题。为了安全起见,您可以使用一个对象来存储全局函数。而不是使用href使用onclick。

    function remove(i) {
      items = items.filter(item => items.indexOf(item) != i);
      render();
    }
    function render() {
  list.innerHTML = '';
  items.map((item, index) => {
    list.innerHTML += `<li><span>${item}</span><a href="javascript: LIB.remove(${index})">X</a></li>`;
  });
}

//所有功能

window.LIB = {
  remove:remove,
  render: render
}

var txt = document.getElementById('ingredients');
var list = document.getElementById('list');
var items = ['PHP', 'React.js', 'WordPress'];

txt.addEventListener('keypress', function(e) {
  if (e.key === 'Enter') {
    let val = txt.value;
    if (val !== '') {
      if (items.indexOf(val) >= 0) {
        alert('Tag name is a duplicate');
      } else {
        items.push(val);
        render();
        txt.value = '';
        txt.focus();
      }
    } else {
      alert('Please type a tag Name');
    }
  }
});
function remove(i) {
  items = items.filter(item => items.indexOf(item) != i);
  render();
}
function render() {
  list.innerHTML = '';
  items.map((item, index) => {
    list.innerHTML += `<li><span>${item}</span><a href="javascript: void 0" onclick="LIB.remove(${index})">X</a></li>`;
  });
}
window.LIB = {
  remove:remove,
  render: render
}


window.onload = function() {
  render();
  txt.focus();
}
<div class="ingredients">
  <ul id="list"></ul>
  <input type="text" id="ingredients" placeholder="type and Enter ...">
</div>

0
投票

您可以尝试将ready函数添加到您的javascript文件中吗?>

$(document).ready(function(){
   var txt = document.getElementById('ingredients');
   var list = document.getElementById('list');
   var items = ['PHP', 'React.js', 'WordPress'];
   .......
});
© www.soinside.com 2019 - 2024. All rights reserved.