Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eval: executing a jquery chain string with dynamic values

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)
}
like image 228
Hodgekinson Avatar asked Aug 17 '26 23:08

Hodgekinson


2 Answers

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.

like image 167
pimvdb Avatar answered Aug 20 '26 14:08

pimvdb


function thisWay(direction) {
    if (direction == 'next') {
        $('#img').next('div');
    }
    else {
        $('#img').prev('div');
    }
}
like image 21
Caimen Avatar answered Aug 20 '26 14:08

Caimen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!