简体   繁体   中英

Pure Js onclick element doesn't work

I'm having trouble when i run this code under greasemonkey the last position working and run function.

var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {  
    document.getElementById('moje_menu').innerHTML = document.getElementById('moje_menu').innerHTML + '<p id="' + arry[i] + '">' + arry[i] + '</p>';
    document.getElementById(arry[i]).onclick = delete;
}

On 10 position the last working ... WHY ????

When you replace the innerHTML you remove all previous event handlers.

In plain JS you can detect the click in the div but you need to check the event :

 function removeP(p) { console.log(p.id); } var arry = ["a","b","c"]; window.onload=function() { for ( var i = 0; i < arry.length; i++) { document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '">' + arry[i] + '</p>'; } document.getElementById('moje_menu').onclick=function(e) { var event = e?e:window.event,tgt = event.target || event.srcElement; if (tgt.tagName.toLowerCase()=="p") { console.log(tgt.id); } } } 
 <div id="moje_menu"></div> 

Alternative is inline since you generate the P anyway

var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {  
    document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="delete(this)">' + arry[i] + '</p>';
}

You can the modify delete (poor name for a function since delete is a built-in method) to handle the passed paragraph

Example:

 function removeP(p) { console.log(p.id); } var arry = ["a","b","c"]; for ( var i = 0; i < arry.length; i++) { document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="removeP(this)">' + arry[i] + '</p>'; } 
 <div id="moje_menu"></div> 

In jQuery you can easily delegate:

 function removeP() { console.log(this.id); } $(function() { var arry = ["a","b","c"]; var $menu = $('#moje_menu'); for (var i=0; i<arry.length; i++) { $menu.append($('<p/>',{"id":arry[i], "text":arry[i]})) } $menu.on("click","p",removeP); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="moje_menu"></div> 

This is my solution i dont like them but works.

var arry = [];
arry = GM_listValues();

for ( var i = 0; i<arry.length; i++) { 

 // if(arry[i].search('player')==''){
    document.getElementById('moje_menu').innerHTML += '<p class="lista_farm" id="'+arry[i]+'">'+arry[i]+'</p>';
    //document.getElementById(arry[i]).onclick = usun_farme;
//}
}
var lista_farm = document.getElementsByClassName('lista_farm');

for(var i = 0; i<lista_farm.length; i++){
  lista_farm[i].onclick = usun_farme;
}

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