用jQuery写一个超过两个子标签就添加删除连接的脚本
时间: 2024-05-15 10:19:55 浏览: 81
以下是一个示例代码,当一个元素有超过两个子标签时,会添加一个“删除”链接,点击该链接将删除元素的最后一个子标签:
```javascript
$(document).ready(function() {
$('body').on('click', '.delete-link', function(e) {
e.preventDefault();
$(this).parent().children().last().remove();
if ($(this).parent().children().length <= 2) {
$(this).remove();
}
});
$('*').each(function() {
if ($(this).children().length > 2) {
$(this).append('<a href="#" class="delete-link">删除</a>');
}
});
});
```
这个脚本添加了一个事件监听器,当用户点击一个“删除”链接时,删除元素的最后一个子标签。如果元素只有两个子标签,该链接也会被删除。在页面加载时,脚本会遍历所有元素,如果一个元素有超过两个子标签,就添加一个“删除”链接。
相关问题
用jQuery在dd标签下添加p标签时超过两个P标签就在p标签里面追加删除连接的脚本
可以使用以下代码实现:
```javascript
$("dd").on("DOMNodeInserted", "p", function() {
if ($(this).siblings("p").length >= 2) {
$(this).append("<a href='#' class='delete'>删除</a>");
}
});
$("dd").on("click", "a.delete", function() {
$(this).parent("p").remove();
});
```
这段代码使用了 jQuery 的 `on()` 方法来监听 `dd` 元素下的 `p` 元素插入事件,并在插入第三个 `p` 元素时在它里面追加一个删除链接。当用户点击删除链接时,它所在的 `p` 元素会被移除。
阅读全文
相关推荐


















