javascript 删除被点击的 <li> onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17012157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:46:16  来源:igfitidea点击:

Remove clicked <li> onclick

javascriptonclick

提问by wondergoat77

I have this JavaScript code:

我有这个 JavaScript 代码:

window.onload = init;

function init () {
    var button = document.getElementById("submitButton");
    button.onclick = addItem;
    var listItems = document.querySelectorAll("li");  //assigning the remove click event to all list items
    for (var i = 0; i < listItems.length; i++) {
        listItems[i].onclick = li.parentNode.removeChild(li);
    }
}

function addItem() {
    var textInput = document.getElementById("item");  //getting text input
    var text = textInput.value;   //getting value of text input element
    var ul = document.getElementById("ul");  //getting element <ul> to add element to
    var li = document.createElement("li");  //creating li element to add
    li.innerHTML = text;    //inserting text into newly created <li> element

    if (ul.childElementCount == 0) {  //using if/else statement to add items to top of list
        ul.appendChild(li);       // will add if count of ul children is 0 otherwise add before first item
    }
    else {
        ul.insertBefore(li, ul.firstChild);
    }
}

function remove(e) {
    var li = e.target;
    var listItems = document.querySelectorAll("li"); 
    var ul = document.getElementById("ul");
    li.parentNode.removeChild(li);        
}

and this HTML:

和这个 HTML:

<body>
     <form>
         <label for="item">Add an item: </label>
          <input id="item" type="text" size="20"><br>
         <input id="submitButton" type="button" value="Add!">
     </form>
     <ul id="ul">
     </ul>
     <p>
         Click an item to remove it from the list.
    </p>  
</body>

What I want to do is remove the whichever <li>element the user clicks, but this doesn't seem to be working and I am unable to find an answer anywhere else online for this specific scenario. Hoping someone can help me out here and show me what i am missing.

我想要做的是删除<li>用户单击的任何元素,但这似乎不起作用,我无法在网上其他任何地方找到针对此特定场景的答案。希望有人能在这里帮助我并向我展示我所缺少的东西。

回答by mplungjan

UPDATE

更新

Plain JS delegation

普通JS委托

Add the eventListener to the UL to delegate the click even on dynamically inserted LIs:

将 eventListener 添加到 UL 以委托点击,即使是在动态插入的 LI 上:

document.getElementById("ul").addEventListener("click",function(e) {
  var tgt = e.target;
  if (tgt.tagName.toUpperCase() == "LI") {
    tgt.parentNode.removeChild(tgt); // or tgt.remove();
  }
});

jQuery delegation

jQuery 委托

$(function() {
  $("#submitButton").on("click",function() {
    var text = $("#item").val();   //getting value of text input element
    var li = $('<li/>').text(text)
    $("#ul").prepend(li); 
  });
  $("#ul").on("click","li",function() {
    $(this).remove();
  });
});   

Original answer

原答案

Since you did not mention jQuery

既然你没有提到jQuery

var listItems = document.getElementsByTagName("li"); // or document.querySelectorAll("li"); 
for (var i = 0; i < listItems.length; i++) {
  listItems[i].onclick = function() {this.parentNode.removeChild(this);}
}

you may want to wrap that in

你可能想把它包起来

window.onload=function() { // or addEventListener
  // do stuff to the DOM here
}

Re-reading the question I think you also want to add that to the dynamic LIs

重新阅读这个问题,我认为您还想将其添加到动态 LI 中

li.innerHTML = text;    //inserting text into newly created <li> element
li.onclick = function() {
  this.parentNode.removeChild(this);
   // or this.remove(); if supported
}

Here is the complete code as I expect you meant to code it

这是完整的代码,因为我希望您打算对其进行编码

Live Demo

现场演示

window.onload=function() {
  var button = document.getElementById("submitButton");
  button.onclick = addItem;
}   

function addItem() {
  var textInput = document.getElementById("item");  //getting text input
  var text = textInput.value;   //getting value of text input element
  var ul = document.getElementById("ul");  //getting element <ul> to add element to
  var li = document.createElement("li");  //creating li element to add
  li.innerHTML = text;    //inserting text into newly created <li> element
  li.onclick = function() {
    this.parentNode.removeChild(this);
    // or this.remove(); if supported
  }
  if (ul.childElementCount == 0) {  //using if/else statement to add items to top of list
    ul.appendChild(li); // will add if count of ul children is 0 otherwise add before first item
  }
  else {
    ul.insertBefore(li, ul.firstChild);
  }
}

In case you want to use jQuery, the whole thing gets somewhat simpler

如果你想使用 jQuery,整个事情会变得更简单

Live Demo

现场演示

$(function() {
    $("#submitButton").on("click",function() {
        var text = $("#item").val();   //getting value of text input element
        var li = $('<li/>')
          .text(text)
          .on("click",function() { $(this).remove()});
        $("#ul").prepend(li); 
    });
});   

回答by Steve Isenberg

I know you already received an answer, but back to your original remove function. You have the following:

我知道你已经收到了答案,但回到你原来的删除功能。你有以下几点:

function remove(e) {
    var li = e.target;
    var listItems = document.querySelectorAll("li"); 
    var ul = document.getElementById("ul");
    li.parentNode.removeChild(li);        
}

Change it to this and you should get what you were trying to achieve:

将其更改为此,您应该得到您想要实现的目标:

function remove(e)
{
   var li = e.target;
   var ol = li.parentElement;
   ol.removeChild( li);
   return false;
}

回答by Uday Hiwarale

If you don't want to write function in javascript, you can use immediately invoked anonymous function like below...

如果您不想在 javascript 中编写函数,则可以使用如下所示的立即调用的匿名函数...

<elem onclick="(function(_this){_this.parentNode.removeChild(_this);})(this);"

回答by David says reinstate Monica

I'd suggest simplifying things a little:

我建议稍微简化一下:

Object.prototype.remove = function(){
    this.parentNode.removeChild(this);
};

var lis = document.querySelectorAll('li');

for (var i = 0, len = lis.length; i < len; i++) {
    lis[i].addEventListener('click', remove, false);
}

JS Fiddle demo.

JS小提琴演示

Of course, having done the above, I'd then have to go further (possibly because I like jQuery too much) and also:

当然,完成上述操作后,我必须更进一步(可能是因为我太喜欢 jQuery)并且:

Object.prototype.on = function (evt, fn) {
    var self = this.length ? this : [this];
    for (var i = 0, len = self.length; i < len; i++){
        self[i].addEventListener(evt, fn, false);
    }
};
Object.prototype.remove = function(){
    var self = this.length ? this : [this];
    for (var i = 0, len = self.length; i < len; i++){
        self[i].parentNode.removeChild(self[i]);
    }
};

document.querySelectorAll('li').on('click', remove);

JS Fiddle demo.

JS小提琴演示

回答by mishik

If I understood you correctly:

如果我理解正确的话:

$("li").on("click", function() {
  $(this).remove()
});

回答by Niccolò Campolungo

The answer is more obvious than it could seem, you forgot to add init()in your script, is normal that the click event aren't triggered, they're not set on the element!

答案比看起来更明显,你忘记添加init()你的脚本,点击事件没有被触发是正常的,他们没有在元素上设置!

EDIT:

编辑

Your code has some logical errors. If you don't add an onclick function for all those created elements you will not be able to remove the clicked element. This is because the function init()is called one time at the load of the page!

您的代码有一些逻辑错误。如果您没有为所有创建的元素添加 onclick 函数,您将无法删除被点击的元素。这是因为该函数init()在页面加载时被调用一次!

function init() {
    var button = document.getElementById("submitButton");
    button.onclick = function() {addItem()};
}

function addItem() {
    var textInput = document.getElementById("item"); //getting text input
    var text = textInput.value; //getting value of text input element
    var ul = document.getElementById("ul"); //getting element <ul> to add element to
    var li = document.createElement("li"); //creating li element to add
    li.innerHTML = text; //inserting text into newly created <li> element
    li.onclick = function() {this.parentNode.removeChild(this);}

    if (ul.childElementCount == 0) { //using if/else statement to add items to top of list
        ul.appendChild(li); // will add if count of ul children is 0 otherwise add before first item
    } else {
        ul.insertBefore(li, ul.firstChild);
    }
}
init();