I have a span tag that looks like the following:
<span class="myClass">Lorem ipsum</span>
I would like to add an attribute to it that references the innerText value (for a javascript function call), and I would like it to look like this:
<span class="myClass" data-bind="click: function(data, event) { myFunction('Lorem ipsum') }">Lorem ipsum</span>
I want to be able to dynamically parse a paragraph of text that contains spans of span myClass, and add the attribute programmatically. As such, if my innerText was “Sed”, the argument to myFunction would be “Sed”.
I tried the following to produce this:
jquery(container).find('.myClass').attr('data-bind', 'click: function(data, event) { myFunction(' + $(this).text() + ')}');
It didn’t work. (The function argument was empty. Trying .html() outputs “null”.)
Does anyone know how to accomplish something like this in jQuery? I believe that my issue is the $(this) keyword, as it’s not pointing to the object in question. I’m not sure if there’s another keyword that I can use…
Thank you!
Edit: Whoops, I attempted to obfuscate my code a little, and forgot to do it for the last line. Sorry for any confusion.
Your code doesn’t work because
$(this)isn’t your element.try:
in this case, $(this) iterates over all the .nonGlassorayKeyword elements, like a for loop.