2

HTML CODE:

<ul id="sortable1" class="connectedSortable ui-sortable">
<li class="ui-state-default" id="1">Name1</li>
<li class="ui-state-default" id="2">Name2</li>
<li class="ui-state-default" id="3">Name3</li>
<li class="ui-state-default" id="4">Name4</li>
<li class="ui-state-default" id="5">Name5</li>

JQUERY CODE:

$(function() {
   $("#sortable1 li").each(function()
   {
        $(this).on("click",make($(this)));
   });

   function make($li)
   {
        alert("hello");
   }
});

fiddle :

http://jsfiddle.net/gztRq/433/

when i run the fiddle , it will automatically displays the alert for five list items. actually i have binded click event for list item so whenever the list is clicked it needs to call the function.

but why the above "make" function triggered five times before am clicking the list. after clicking the list item nothing happened. what is the problem ?

when i write the function code in-line everything works as expected.

Working code:

 $("#sortable1 li").each(function()
 {
    $(this).on("click",function()
    {
      alert("hello");
    });
 });

what is the correct behavior ?

5 Answers 5

3

Remove the $.each() loop completely and just use:

$('#sortable1').on('click', 'li', function() {
    alert("Hello"); // Or make($(this)); if you still want that extra function
});

JSFiddle demo.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. i knew that why it was not working in each function. anything wrong in code ?
@SivaRajini I'm not sure what you mean.
your answer u mentioned remove $.each loop completely. what is the reason ? why we can't bind the click event is each function ?
@SivaRajini because there's no need for it. $('#sortable1').on('click', 'li', ...) adds a click event to all the li items contained within #sortable1.
3

You call your function, don't add "(", ")". Just write name function (is reference). And this, is already define for the event function. http://jsfiddle.net/gztRq/437/

$(function() {    
   $("#sortable1 li").each(function() {
       $(this).click(make);
   });
   function make() {
        alert("hello "+$(this).text()); 
   }
});

Comments

1

You should use:

 $(this).on("click",function(){make($(this))});

Demo

Comments

0

Try this,

$("#sortable1 li").click(function(){
     make($(this));
});

1 Comment

why that one not working in each function ? what is the correct behavior ?
0

you can try:

$(document).on("click","sortable1 li",function(){

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.