I am making a phonegap program and I want to use a .on('tap')
event instead of onClick="blah(param1,param2)"
because of the 400ms delay. What I wanted to do was give a list of "tappable" items a class of "button1" and with each item give it a data-meth="dosomething3()"
and then retrieve that when something is tapped. So far my example does not use tap but click instead.
<script>
$(document).ready(function() {
console.log('document ready');
$(".button1").on('click', function(e){ //this will changed to 'tap' eventually
e.preventDefault();
console.log("logged click");
var tempp=$(this).data("meth");
alert(tempp);
tempp; // thought this would call the function as it is written in the data-meth value but it doesn't
});
});
function dosomething(){
console.log('dosomething called');
}
function dosomething(var1,var2){
alert('hello:' +var1+' just showing var2'+var2);
}
</script>
My simple html is
<ul>
<li style="text-align:center" class="button1" data-meth="dosomething()" >One</li>
<li style="text-align:center" class="button1" data-meth="dosomething2(var1,var2)">Two</li>
<li style="text-align:center" class="button1" data-meth="dosomething3()">Three</li>
</ul>
How can i grab and call the function based or what is stored in the data-meth value?
Off the top of my head:
$(".button1").click(function() {
var functionName = $(this).attr("data-meth").split("(")[0];
var functionParams = $(this).attr("data-meth").split(")")[0].split[","];
window[functionName](functionParams);
});
functionParams
would be an array containing your values. That may or may not be what you need. You could also use the ever-evil eval
like so:
$(".button1").click(function() {
eval($(this).attr("data-meth"));
});
In which case you could pass in your parameters and treat them as usual.
eval()
. Google its shortcomings before you use it again. It's probably okay in this case, though - Elliot Bonneville 2012-04-05 17:27