【问题标题】:Fire an event when a liste get new item当列表获得新项目时触发事件
【发布时间】:2021-04-11 12:44:53
【问题描述】:

我有一个空列表:

<ul id="select2-choices"></ul>

这个列表使用 ui 获取添加到其中的元素,所以我得到了这个:

 <ul id="select2-choices">
   <li>item1</li>
   <li>item2</li>
 </ul>

我想触发一个事件,以便在该列表获得新项目时调用一个函数:

$("#select2-choices").on("Thevent", function (e)){
            self.SetDefaultTeam(e);
        });

怎么做?

【问题讨论】:

  • 将内容添加到 DOM 时不会引发事件。您是否控制附加新 li 元素的 JS 代码?如果是这样,您可以使用trigger() 手动引发事件。如果你不控制 JS,那么你可以使用 MutationObserver
  • 什么创建列表项以及如何创建?您遗漏了问题的重要部分。

标签: javascript jquery dom


【解决方案1】:

您可以使用如下所示的变异观察者。代码已注释。我创建了一个按钮来模拟新项目的添加,但突变观察者是识别 DOM 树中变化的函数。

注意如果您有权访问添加新 li 的代码,那么最好从那里触发您的函数。

如果您还希望有别的东西,请告诉我。


// Create a button to add options to mimic your functionality
$("#add-li").click(function() {
  $("ul#select2-choices").append("<li>New</li>");
});

// Create mutation observer
var observer = new MutationObserver(function(mutations) {
  
    // Something has changed in the #select2-choices
    console.log("Change noticed in childList");
    
});

// Just look out for childList changes
var config = {
  attributes: false,
  childList: true,
  characterData: false
};

// Select target
var target = document.querySelector('#select2-choices');

// Launch observer with above configuration
observer.observe(target, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="select2-choices">
</ul>

<button id="add-li">Add option</button>

【讨论】:

    猜你喜欢
    • 2019-08-18
    • 2010-10-18
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多