英文:
Using Jquery to check if items have been added to a list by user
问题
我有一个列表,用户可以使用下拉菜单添加项目。我正在跟踪用户行为,并希望在用户每次添加某些内容到此列表时执行一个函数(不是移除它)。列表看起来像这样:
<ul class="items-list" id="user-items">
<li id="newitem1"></li>
<li id="newitem2"></li>
</ul>
他们可以使用下拉菜单添加更多项目到列表中,问题是没有用于这些项目链接的jQuery选择器,因此我尝试检测何时添加项目到列表中。
我迄今为止的尝试是:
var listOfItems = $("#user-items").children();
我可以计算列表中当前有多少个项目。但是我无法弄清楚如何检查用户是否添加了更多项目。我是jQuery的新手,如果有人能指导我正确的方向,我将不胜感激。谢谢。
英文:
I have a list which users can add items to using a drop down of items. I'm tracking user behavior and want to execute a function each time a user ADDS something to this list (not removes it). The list looks like this:
<ul class="items-list" id="user-items">
<li id="newitem1"></li>
<li id="newitem2"></li>
</ul>
They can add more items to the list with the dropdown, the issue is there are no Jquery selectors for the links to those items, so I am instead trying to detect when items are added to the list.
My attempts so far are:
var listOfItems = $("#user-items").children()
- I can count how many items are currently in the list. However I can't work out how to check whether the user has added more items. I am new to Jquery and would appreciate if someone could point me in the right direction here? Thanks
答案1
得分: 2
使用DOMSubtreeModified事件并检查是否向DOM添加了新元素。
$("#a").bind("DOMSubtreeModified", function() {
alert("列表已更新");
});
演示:
Fiddle链接
英文:
Use DOMSubtreeModified event and check if new element added to DOM.
$("#a").bind("DOMSubtreeModified", function() {
alert("list updated");
});
Demo:
Fiddle
答案2
得分: 0
所有下拉列表的值在添加新项目之前都可以使用Jquery的.each()方法进行检查。
<ul class="items-list" id="user-items">
<li id="newitem1"></li>
<li id="newitem2"></li>
</ul>
Jquery代码:
$("li").each(function(index) {
console.log(index + ": " + $(this).text());
});
参考链接:https://api.jquery.com/each/
<details>
<summary>英文:</summary>
All the values of dropdown can be checked using Jquery .each() before adding new item.
<ul class="items-list" id="user-items">
<li id="newitem1"></li>
<li id="newitem2"></li>
</ul>
Jquery:
$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
Reference : https://api.jquery.com/each/
</details>
# 答案3
**得分**: 0
你可以观察DOM的特定部分中的变化,并在发生变化时执行任何你想要的操作。
文档链接:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
示例:
```javascript
const itemsList = document.querySelector("#user-items");
const observer = new MutationObserver((mutationList, observer) => {
mutationList.forEach((mutation) => {
if (mutation.type === "childList") {
// 在这里执行你想要的操作,我只是记录一个子节点已经被添加。
console.log("A child node has been added");
}
});
});
observer.observe(itemsList, { childList: true, subtree: true });
/**
* 只是一些基本的代码来向列表添加项目。不是jQuery,但
* 我假设你已经有了这个代码,所以这里只是为了使
* 演示工作。
*/
const itemAdder = document.querySelector("#add-item");
let itemNumber = 0;
itemAdder.addEventListener("click", (e) => {
itemNumber++;
const listItem = document.createElement("LI");
listItem.setAttribute("id", `user-item-${itemNumber}`);
const listItemText = document.createTextNode(`List item ${itemNumber}`);
listItem.appendChild(listItemText);
itemsList.appendChild(listItem);
});
<ul id="user-items">
</ul>
<button id="add-item">Add Item</button>
英文:
You can observe mutations in that specific part of the DOM and do whatever you want when they occur.
Documentation here: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const itemsList = document.querySelector("#user-items");
const observer = new MutationObserver((mutationList, observer) => {
mutationList.forEach((mutation) => {
if (mutation.type === "childList") {
// Do whatever you want here, I'm just logging that
// a child of the <ul> has been added.
console.log("A child node has been added");
}
});
});
observer.observe(itemsList, { childList: true, subtree: true });
/**
* Just some basic code to add items to the list. Not jQuery, but
* you already have this code I assume, so this is just here to make
* the demo work
*/
const itemAdder = document.querySelector("#add-item");
let itemNumber = 0;
itemAdder.addEventListener("click", (e) => {
itemNumber++;
const listItem = document.createElement("LI");
listItem.setAttribute("id", `user-item-${itemNumber}`);
const listItemText = document.createTextNode(`List item ${itemNumber}`);
listItem.appendChild(listItemText);
itemsList.appendChild(listItem);
});
<!-- language: lang-html -->
<ul id="user-items">
</ul>
<button id="add-item">Add Item</button>
<!-- end snippet -->
答案4
得分: 0
您可以通过使用MutationObserver
来实现这一点。MutationObserver接口
提供了监视对DOM树
进行更改的能力。它被设计为旧的Mutation Events功能的替代品,后者是DOM3
事件规范的一部分。
以下是一个工作示例。
var targetNode = $("#user-items");
function createObserver(callback) {
return new MutationObserver(function (mutationRecords) {
mutationRecords.forEach(callback);
});
}
$("#user-items").each(function () {
var obs = createObserver(function (mutation) {
$(mutation.addedNodes).css("background-color", "green");
});
obs.observe(this, { childList: true });
});
setTimeout(function(){
$("#user-items").append('<li id="newitem3">New One</li>');
},1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<ul class="items-list" id="user-items">
<li id="newitem1">Old One</li>
<li id="newitem2">Old two</li>
</ul>
这是您提供的代码的翻译部分。
英文:
You can achieve so by using MutationObserver
.The MutationObserver interface
provides the ability to watch for changes being made to the DOM tree
. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3
Events specification.
here is a working example.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var targetNode = $("#user-items");
function createObserver(callback) {
return new MutationObserver(function (mutationRecords) {
mutationRecords.forEach(callback);
});
}
$("#user-items").each(function () {
var obs = createObserver(function (mutation) {
$(mutation.addedNodes).css("background-color", "green");
});
obs.observe(this, { childList: true });
});
setTimeout(function(){
$("#user-items").append('<li id="newitem3">New One</li>');
},1000)
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<ul class="items-list" id="user-items">
<li id="newitem1">Old One</li>
<li id="newitem2">Old two</li>
</ul>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论