简体   繁体   中英

How to make JS framework custom functions work for dynamically added elements?

I'm using @material/select. Options are added from JS script after AJAX call: (Simplified code)

for (let key in data.directories){
    $("#selector-options").append('<li data-value="'+data.directories[key]+'" role="option">\n' +
        '                             <span>'+data.directories[key]+'</span>\n' +
        '                          </li>')
}

And the Material listener code looks like this (Fires when user chose an option):

import {MDCSelect} from '@material/select';
const select = new MDCSelect(document.querySelector('.mdc-select'));
select.listen('MDCSelect:change', () => {
    alert(`Selected option at index ${select.selectedIndex} with value "${select.value}"`);
});

What I have to do is make an AJAX request when user choose an option, but MDCSelect code runs before AJAX request (to get data ), and generated options are not handled correctly. How can I make MDCSelect code run after AJAX request? Also I can dynamically add options using PHP, but can I make it using JS only?

Solved by including a PHP script into admin.blade.php (Laravel):

@for ($i=0;$i<count($directories);$i++)
   <li class="mdc-list-item" aria-selected="false" data-value="{{$directories[$i]}}" role="option">
     <span class="mdc-list-item__ripple"></span>
     <span class="mdc-list-item__text">{{$directories[$i]}}</span>
   </li>
@endfor

Now everything works fine, but I feel sad

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