javascript 通过点击直接删除 <li>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4417164/
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-25 11:21:40  来源:igfitidea点击:

Remove <li> directly by an onclick

javascripthtml

提问by Yan

Any way to remove "li" directly without javascriptjust with onclick?

有什么方法可以不用javascript直接删除“li”,只需使用onclick?

$go .="<li id=\"go_$id\"><a ondblclick=\"g('$id'); return false;\">$title</a>
             <a onclick=\"go('$id', 'g')\">(x)</a>
    </li>\n";

I need it to be removed by clicking on (x), so together with my other function (onclick function in the code) to combine the remove so that that "li" will disappear onclick.

我需要通过单击 (x) 来删除它,因此与我的其他函数(代码中的 onclick 函数)一起删除,以便“li”在单击时消失。

回答by BalusC

Use Node.parentNodeto obtain the parent node and use Node.removeChild()to remove a child node. Here's the self-explanatory version of the code:

使用Node.parentNode获得的父节点和使用Node.removeChild()删除子节点。这是代码的不言自明的版本:

<li><a href="#" onclick="var li = this.parentNode; var ul = li.parentNode; ul.removeChild(li);">remove</a></li>

Here's a more short version:

这是一个更简短的版本:

<li><a href="#" onclick="parentNode.parentNode.removeChild(parentNode)">remove</a></li>

Here's how to use it in combination with a JS function:

下面是结合JS函数使用的方法:

<li><a href="#" onclick="remove(this)">remove</a></li>

with

function remove(link) { 
    link.parentNode.parentNode.removeChild(link.parentNode);
}

回答by ?ime Vidas

If you chose to separate content from behavior (HTML from JavaScript), then this would work just fine (using jQuery):

如果您选择将内容与行为(HTML 与 JavaScript)分开,那么这将工作得很好(使用 jQuery):

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

Edit:

编辑:

$("li a").click(function() { $(this).closest("li").remove(); }); 

However, I recommend a more specific selector - like .closeButton

但是,我推荐一个更具体的选择器 - 比如 .closeButton

回答by David_001

No.

不。

Not without JavaScript.

不是没有 JavaScript。

回答by Oded

If using IE, you can do it with VBScript.

如果使用 IE,您可以使用VBScript 来完成

In order to change a loaded page dynamically, you will have to use client side scripting of one kind or another (java, javascript, vbscript - depending on what browser and installed plugins).

为了动态更改加载的页面,您必须使用一种或另一种客户端脚本(java、javascript、vbscript - 取决于浏览器和安装的插件)。

回答by Alejandro Ruiz Avi?a

function remove_item(selected_item) {
        selected_item.parentNode.removeChild(selected_item);
    }
    li {
        background: #ffe5e5;
        padding: 20px; 
        margin: 15px;
        list-style-type: decimal;
    }
<ul id="list">
        <li class="one" onclick="remove_item(this)">React</li>
        <li class="one" onclick="remove_item(this)">Node.js</li>
        <li class="one" onclick="remove_item(this)">Dart</li>
</ul>