I want to pass parameter when I click in <a href>
, first I have this and works fine:
<a href="#" rel="like{{num}}"> I like </a>|
$("a[rel^='like']").click(function(){
$.ajax({
...
});
but I don't know how to pass parameter to that function, so I do this:
<a href="#" rel="like{{num}}"
onclick="cap(para1, para2)"> I like </a>
Finally, in my Javascript I have this simple function:
function cap(para1, para2){
alert('here');
}
but I obtain this error:
ReferenceError: cap is not defined
Any idea?
I want to pass parameter when I click in <a href>
, first I have this and works fine:
<a href="#" rel="like{{num}}"> I like </a>|
$("a[rel^='like']").click(function(){
$.ajax({
...
});
but I don't know how to pass parameter to that function, so I do this:
<a href="#" rel="like{{num}}"
onclick="cap(para1, para2)"> I like </a>
Finally, in my Javascript I have this simple function:
function cap(para1, para2){
alert('here');
}
but I obtain this error:
ReferenceError: cap is not defined
Any idea?
Share Improve this question edited Nov 26, 2012 at 14:32 JeanValjean 17.7k23 gold badges116 silver badges161 bronze badges asked Oct 26, 2012 at 8:17 user852610user852610 2,2657 gold badges36 silver badges46 bronze badges 1-
Would this
cap
function happen to be inside of a$(document).ready()
callback? – Blender Commented Oct 26, 2012 at 8:19
3 Answers
Reset to default 6A solution is to use data attributes :
<a href="#" rel="like{{num}}" data-para1="Oh" data-para2="{{somepara}}"> I like </a>
<script>
function cap(para1, para2){
alert('here');
}
$("a[rel^='like']").click(function(){
var para1 = this.dataset['para1'];
var para2 = this.dataset['para2'];
cap(para1, para2);
});
</script>
You may also write it like this if you prefer a more structured approach :
<a href="#" rel="like{{num}}" data-params="{'para1':'Oh','para2':'{{somepara}}'}"> I like </a>
$("a[rel^='like']").click(function(){
var params = this.dataset['params'];
var para1 = params.para1;
var para2 = params.para2;
Note that if the document isn't an HTML5 document you'll have to use the more patible data function of jQuery (but there hardly is any reason not to use HTML5 doctype today) :
var para1 = this.data('para1');
You may like to try this.
<a class="ilike" href="javascript:;" data-p1="abc" data-p2="123"> I like </a>
<script>
function cap(para1, para2){
alert('here');
}
$(function(){
$('.ilike').click(function(){
var $this = $(this);
var p1 = $this.data('p1');
var p2 = $this.data('p2');
cap(p1, p2);
});
});
</script>
If you want to do it via onclick, it's either that 1) you have declared your function in wrong scope or 2) another JS error occurred before the function declaration and caused it to not be executed.
To fix the scope problem, you can try doing window.cap = function(para1, para2) { ...
To see if there are any errors, try something like firebug or any browser developer tools and check for errors under console.