G
G
G0rDi2011-03-10 09:13:06
JavaScript
G0rDi, 2011-03-10 09:13:06

Passing parameters to a function when clicking on a link (JQuery)?

In pure JavaScript, it looks something like this:

&lt;sсript&gt;<br/>
function toFunction(m1, m2) {<br/>
 alert(m1 + ' - ' + m2);<br/>
}<br/>
&lt;/sсript&gt;<br/>
&lt;а href=&quot;javascript:toFunction(10,'text')&quot; &gt;Ссылка&lt;/а&gt;


And here's how to do it according to jQuery rules:

&lt;sсript&gt;<br/>
$(document).ready(function() {<br/>
 $(&quot;.urlparam&quot;).click(function () {<br/>
<br/>
alert(m1 + ' - ' + m2);<br/>
<br/>
});<br/>
});<br/>

<a href="#" class="urlparam" >Link</a>

Answer the question

In order to leave comments, you need to log in

6 answer(s)
S
Sererator, 2011-03-10
@Serator

Perhaps it makes sense to use the data-* attribute from html5, instead of crutches on class / rel / etc., which are not intended for this?
+ use of javascript pseudo-protocol: evil ;).

H
homm, 2011-03-10
@homm

With what fright my code cannot be used for several links, I did not understand.
Once:

function toFunction(){};
$(".urlparam1").click(function () { toFunction(10,'text'); });
$(".urlparam2").click(function () { toFunction(9,'text1'); });

Two:
function toFunction(){};
$(".urlparam1").click({num: 10, text: 'text'}, toFunction);
$(".urlparam2").click({num: 9, text: 'text1'}, toFunction);

Input inside the link is a complete tin. If you really need to store some data directly in the DOM tree, use valid data attributes:
<а href="#" class="urlparam" data-num="10" data-text="text"></a>
<а href="#" class="urlparam" data-num="9" data-text="text1"></a>

$(".urlparam").click(function () {
    var num = $(this).data('num');
    var text = $(this).data('text');
});

H
homm, 2011-03-10
@homm

First, you can use eventData (see api.jquery.com/click/ ).
Second, you can still write:

$(".urlparam").click(function () {
    toFunction(10,'text');
});

V
Vlad Frolov, 2011-03-10
@frol

Interest Ask. If I need one parameter, then I use the href="#" attribute. If there are several parameters: PS And I also use rel instead of class.
<а href="#" class="urlparam">
Ссылка
<input type="hidden" name="param1" value="1">
<input type="hidden" name="param2" value="2">
</а>
$(".urlparam").click(function () {
var param1 = $(self).find('param1').val();
});

S
seagull, 2011-03-10
@seagull

$('.urlparam').each(function(index) {
    $(this).click({num: (index+1), text: $(this).value()},toFunction);
  });

N
nikitammf, 2011-03-10
@nikitammf

I like this way .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question