1

From jQuery website:

.on( events [, selector ] [, data ], handler(eventObject) )

How can i write a correct code to pass a parameter from ON method to the event handler Function...

I want a code like this:

myfunc =function(obj){
$(this).after("<p>Another paragraph! "+obj+"</p>");
}

var count = 0;
$("body").on("click", "p",myfunc(++count) );

enter image description here

2 Answers 2

4
myfunc =function(event){
    $(this).after("<p>Another paragraph! "+event.data+"</p>");
}

$("body").on("click", "p", ++count, myfunc);

The data you send is being inserted to the event object:

data

Data to be passed to the handler in event.data when an event is triggered.

docs

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

8 Comments

@Nelson, it works just fine, this is how you pass values, if you want the value to change, you will need to use different methods then the OP asked.
Ok, I didn't understand the question right then.. sorry for the noise.
it is ok, but i want to increment the count every time the P is clicked, not cache the value
@Ram, then use James's answer.
i want define the function out of ON() method and set it as the eventHandler
|
3

Assuming you intend to increment the count on every click:

var count = 0;
$("body").on("click", "p",function(){
    $(this).after("<p>Another paragraph! " + (++count) + "</p>");
});

Edit, if you want your function to be separate and don't want to change it, you can do this:

myfunc = function(obj){
    $(this).after("<p>Another paragraph! "+obj+"</p>");
}

var count = 0;
$("body").on("click", "p",function(){
    myfunc.call(this, ++count);
});

http://jsfiddle.net/Bwk3W/

7 Comments

That doesn't equal to the code he tried, your code doesn't save the value of count, it can change before the event will fire.
@gdoron that's what the 2nd bit in the answer is about. Though lookign at it again, I think both of our answers are wrong. I believe he wants to increment the count on every click, not cache the value.
+1, well it seams that he wants your answer, I'll give my answer live because It better answer the question text...
@JamesMontagne, i know your answe is correct, but i want an answer like gdoron answer
@RAM Updated my answer. If this isn't what you want either then you'll need to explain your question better.
|

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.