0

I currently have a piece of code as follow:.

var nextSibling = $(this.parentNode).next();

what I would like to do is potentially change the next() function to prev(), depending on the keypress. (I expect this to be an input element in a table).

How do I put the next() / prev() functions into variables (I am guessing you access it through some prototype object, but I am not sure which one).

if (keypressRight){ 
    var nexOrPrev =  SomeObject.prototype.next
}else{
    var nextOrPrev =  SomeObject.prototype.prev
}

Then to call it , I assume I would do the following :

 var nextSibling = $(this.parentNode).nextOrPrev()

Does that look like the correct way of doing things? I am open to suggestions of better ways. (I saw somewhere else suggesting using apply for the function call, but I don't currently see any benefit in using this).

2 Answers 2

3

You can use bracket notation to call function on a jQuery object. Try this:

var funcName = keypressRight ? 'next' : 'prev';
var nextSibling = $(this.parentNode)[funcName]();
Sign up to request clarification or add additional context in comments.

Comments

1

you may write

var nextOrPrev =  SomeObject.prototype[keypressRight?"next":"prev"];

using the ternary operator

and this can be done also for

$(this.parentNode)[keypressRight?"next":"prev"]();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.