How to use the onclick event in a list (jqueryui-selectable)?


I created a simple script with jqueryui-selectable list. I generate a selectable list and assign each list with an onclick function. It seems that the onclick event was not triggered when I clicked the list. Any idea to solve this problem?


my script:

$(document).ready(function() {

function generate(){
var $content=$("<ol id='selectable'>");
for (a=0;a<3;a++)
$content.append("<li class='ui-widget-content'  onclick='myFunction()'>item"+a+"</li>");

function myFunction()
alert("Hello World!");

my style:

#feedback { font-size: 1.4em; }
#selectable .ui-selecting { background: #FECA40; }
#selectable  .ui-selected { background: #F39814; color: white; }
#selectable  { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#selectable  li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }

my html:

<div id='myList'/>
<button id="myButton" onClick="generate()">Generate List</button>

Since the element is dynamically created, it needs to be delegated. You can do this in jQuery by:

$(document).on("click",".ui-widget-content", myFunction());

(Or just use an anonymous function)

$(document).on("click",".ui-widget-content", function() {
    alert("Hello World!");