0

Some code of mine uses jquery to create elements <a> with a function given for click behavior:

$(alternatives).each(function (idx, elt) {
  var element = $('<span class="label label-success">');
  var link = $('<a class="prop' + idx + '" title="' + elt + '">' + elt + '</a>');
  link.click(switchLabel);
  element.append(link);
  list.append(element);
});

The idea here is to catch the click event on the <a class="prop1-0" title="myTitle">my link</a> to change the text in a <span id="corr1-0">my old text</span>. The link between both element is made by the class suffix, f.i. 1-0.

I have several pairs <a>/<span>, I checked every id.

Some links work, but some do not: no error in console, nothing to trace with firebug...

The function binded is :

function switchLabel(e) {
  $('#corr'+ e.target.className.substr(4)).text($(e.target).attr('title'));
}

Do you have some tips to help me track this unwanted behavior? May I make a mistake in the implementation?

Regards

2
  • first of all you are using the variable index and idx, is that right? Commented May 13, 2013 at 15:32
  • Yeah, it is a typo... Commented May 14, 2013 at 7:26

1 Answer 1

4

Your variables don't match, you are using index and not idx etc. and there are easier ways to create elements and event handlers ?

$.each(alternatives, function (idx, elt) {
    var element = $('<span />', {'class' : 'label label-success',
                                 id      : 'corr'+idx
                                }
        ),
        link    = $('<a />' {id    : 'prop' + idx, 
                             title : elt, 
                             text  : elt
                            }
        );
    link.on('click', function() {
        $('#' + this.id.replace('prop','corr')).text(this.title);
    });
    list.append( element.append(link) );
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for sharing. I did not know this syntax and after a quick look, it seems much more stable. Why? Is my code wrong or is a framework matter?
This code creates a link in a bootstrap popover element. This element, created and displayed/hidden by bootstrap code, does not handle correctly because at first call, the click event is launched, while in the other calls (after a cycle hidden/shown back), it is not...

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.