In these cases it is better to create the element in another line and use the jQuery methods to put the dynamic values in place:
var button = $("<button class='ui-btn ui-corner-all optCurso' data-transition ='slide'></button>");
button.click(function () { controller.setNomeCurso(cursos[i].Value); });
button.text(cursos[i].Name);
$("#cursos").append(button);
(depending exactly where it comes from i
, maybe you need something like button.click((function (nomeCurso) { return function () { controller.setNomeCurso(nomeCurso); }})(cursos[i].value));
to capture right to closure)
You’ll also need to put one type="button"
if this button appears inside a form.
You really need to do this with jQuery?
var button = document.createElement('button');
button.type = 'button';
button.className = 'ui-btn ui-corner-all optCurso';
button.setAttribute('data-transition', 'slide');
button.addEventListener('click', function () { controller.setNomeCurso(cursos[i].Value); }, false);
button.appendChild(document.createTextNode(cursos[i].Name));
document.getElementById('cursos').appendChild(button);
This works on any IE 8+; if you agree to only be compatible with IE 11 and Edge, you can switch button.setAttribute('data-transition', 'slide')
for button.dataset.transition = 'slide'
.
The jQuery encourages this style of code, concatenating strings; this problem you encountered is the newest prime of SQL Injection. Concatenating strings to generate HTML tags is asking you to create XSS holes in your application.
Hello my friend, thank you so much for your help. My
i
comes from a bowfor
that exists. I tried the first option, but unfortunately it didn’t work. The error generated was:Uncaught ReferenceError: cursor is not defined
this right on the line where you add the event click. The second option also failed, returned the following error:ncaught TypeError: Cannot read property 'Value' of undefined
.– Jedaias Rodrigues
Mea culpa, I had a typo of courses for cursor (corrected)
– user25930
I had noticed and fixed when testing on my code, the problems unfortunately persist, there is no way to fix the code posted by @alysonsm ?
– Jedaias Rodrigues