使用Jquery检查用户是否已向列表中添加项目

huangapple go评论84阅读模式
英文:

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:

&lt;ul class=&quot;items-list&quot; id=&quot;user-items&quot;&gt;
  &lt;li id=&quot;newitem1&quot;&gt;&lt;/li&gt; 
  &lt;li id=&quot;newitem2&quot;&gt;&lt;/li&gt;
&lt;/ul&gt;

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 = $(&quot;#user-items&quot;).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.

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

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(&quot;#user-items&quot;);

const observer = new MutationObserver((mutationList, observer) =&gt; {
  mutationList.forEach((mutation) =&gt; {
    if (mutation.type === &quot;childList&quot;) {
      // Do whatever you want here, I&#39;m just logging that
      // a child of the &lt;ul&gt; has been added.
      console.log(&quot;A child node has been added&quot;);  
    }
  });
});

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(&quot;#add-item&quot;);
let itemNumber = 0;

itemAdder.addEventListener(&quot;click&quot;, (e) =&gt; {
  itemNumber++;
  const listItem = document.createElement(&quot;LI&quot;);
  listItem.setAttribute(&quot;id&quot;, `user-item-${itemNumber}`);
  const listItemText = document.createTextNode(`List item ${itemNumber}`);
  listItem.appendChild(listItemText);
  itemsList.appendChild(listItem);
});

<!-- language: lang-html -->

&lt;ul id=&quot;user-items&quot;&gt;
&lt;/ul&gt;

&lt;button id=&quot;add-item&quot;&gt;Add Item&lt;/button&gt;

<!-- 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 = $(&quot;#user-items&quot;);
function createObserver(callback) {
    return new MutationObserver(function (mutationRecords) {
        mutationRecords.forEach(callback);
    });
}

$(&quot;#user-items&quot;).each(function () {
    var obs = createObserver(function (mutation) {
        $(mutation.addedNodes).css(&quot;background-color&quot;, &quot;green&quot;);
    });
    obs.observe(this, { childList: true });
});



setTimeout(function(){
  $(&quot;#user-items&quot;).append(&#39;&lt;li id=&quot;newitem3&quot;&gt;New One&lt;/li&gt;&#39;);
},1000)

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;ul class=&quot;items-list&quot; id=&quot;user-items&quot;&gt;
  &lt;li id=&quot;newitem1&quot;&gt;Old One&lt;/li&gt; 
  &lt;li id=&quot;newitem2&quot;&gt;Old two&lt;/li&gt;
&lt;/ul&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月3日 19:18:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定