I would like to execute this jQuery string but so far the only way I know how is to use eval, what is a more appropriate way of doing this?
var first = thisWay('next')
var second = thisWay('prev')
var thisWay = function(direction){
var Chain = "$('#img')." + direction + "('div');";
eval(Chain)
}
There is another way of accessing properties using the [] notation. That way you can pass dynamic values as well:
$('#img')[direction]('div');
To be precise, $(...).something is equal to $(...)['something']. So passing something after . is always a literal string, while [...] does not necessarily have to be a literal string.
function thisWay(direction) {
if (direction == 'next') {
$('#img').next('div');
}
else {
$('#img').prev('div');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With