Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Broken jQuery code, need help.

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #175537
    Chris Lowles
    Participant

    Hello again, been a while, nevertheless I got stuck… again.

    This time I’ve been stuck trying to figure out the ternary operator in a jQuery function, it’s apart of a function I’m making.

    $(this).attr(tn1, tn2 ? tn1, tn2 : tn1, tn3);

    But its returning an error: Uncaught SyntaxError: Unexpected token ,

    Wat do?

    #175550
    Chris Lowles
    Participant
    $.fn.textnet = function(tn, tn1, tn2, tn3) {
            if (tn == "toggleAttr") {
                    $(this).attr(tn1, tn2 ? tn1, tn2 : tn1, tn3);
            }
    };
    
    #176085
    TheDutchCoder
    Participant

    My best guess is he wants to trigger tn1 and tn2 if they’re supplied, but if tn2 isn’t supplied he wants to trigger tn1 and tn3 instead.

    Now that’s perfectly fine, but you need a lot more to make this even remotely safe ;-)

    try this:

    $.fn.textnet = function(tn, tn1, tn2, tn3) {
      if (tn === 'toggleAttr') {
        if ((tn1 && tn1 !== 'undefined') && (tn2 && tn2 !== 'undefined')) {
          $(this).attr(tn1, tn2);
        } else if ((tn1 && tn1 !== 'undefined') && (tn3 && tn3 !== 'undefined')) {
          $(this).attr(tn1, tn3);
        } else {
          // None of the conditions are met.
          // E.g. tn2 and tn3 are missing.
        }
      }
    }
    

    Remember you HAVE to supply tn2, even if you only want to trigger tn3, like so: $('.something').textnet('toggleAttr', 'href', null, '#foobar');

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.