简体   繁体   中英

Using Jquery to check if items have been added to a list by user

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

Use DOMSubtreeModified event and check if new element added to DOM.

$("#a").bind("DOMSubtreeModified", function() {
    alert("list updated");
});

Demo: Fiddle

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/

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:

 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); });
 <ul id="user-items"> </ul> <button id="add-item">Add Item</button>

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.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM