简体   繁体   中英

JQuery create element and execute function upon clicking it

For a web based project, I am using jQuery. In one part of the code, there is data that gets dynamically added to the screen on the client side based on the activity of other users connected to the server. I want to write a code that will allow me to execute a function when a client clicks on the data.

To elaborate a little bit, there is a list which shows which members are online. When a new client connects, his name is added to the list and all other users can see on their screen that he is online. When another user clicks on his name, he sends a message request.

This is the relevant jQuery code:

$('#inc').append("<br><i onclick='accept()'>"+data.plr+"<i><br>")

And the accept function is defined under this block which is within another function, so like

function a(){
     $('#inc')....
}
function accept(){
    //...
}

However, when the code runs I get an error which says accept() is not defined

How do I solve this problem?

Maybe you can do it in that way...

$('#inc').append("<br><i>"+data.plr+"<i><br>")
$('#inc i:last-child').click(accept);

I did a small CodePen to let you see the code in action https://codesandbox.io/embed/frosty-jang-fvk3j

I've always done it this way. I find this easier.

$('#inc').append("<br><i class="child">"+data.plr+"<i><br>")

$('.child').on("click",function(){
//your code here
});

You can do it with this way as well :

jQuery(function(){
      click_link = $('<a class="" href="#">Click here</a>');
      click_link .bind("click", function(){
        alert('DO something');
      });

      $('.your_dom').append(click_link );
    });

Write it using jQuery methods:

var $i = $('<i>').text(data.plr).click(function(event) {
    //handle here onClick event
}); //or if you have the function already declared just write .click(accept);

$('#inc').append('<br />', $i, '<br />');

https://api.jquery.com/click/

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