Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - Fire an event when a liste get new item

i have an empty list :

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

this list gets elements added to it using a ui ,so i get this :

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

i want to fire an event , in order to call a function when that list get a new item :

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

how to do that ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use mutation observers as shown below. The code is commented. I created a button to mimic the addition of new items, but the mutation observer is the function that recognises that change in the DOM tree.

N.B. If you have access to the code that is adding the new li then it would be better to trigger your function from there.

Let me know if you were hoping for something else.


// 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...