Reputation: 63
I am generating links from json files on the client side.
loadSubjects = function() {
return importData("themen", function() {
var i, _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = data.themen.themen.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
$("#subjectBtns").append('<a href="javascript:generateSubjectOverview("' + data["themen"]["themen"][i]["dateiName"] + '");" class="btn btn-mghg">' + data["themen"]["themen"][i]["name"] + '</a>');
console.log('appending: ' + '<a href="javascript:generateSubjectOverview("' + data["themen"]["themen"][i]["dateiName"] + '");" class="btn btn-mghg">' + data["themen"]["themen"][i]["name"] + '</a>');
_results.push(false);
}
return _results;
});
};
I also tired onlick instead of href, but that also didnt work. I am getting the error:
Uncaught SyntaxError: Unexpected end of input
The javascript code looks somewhat messy, but that is, because it´s generated by coffeescript.
the function importData
is just a short hand for $.getJSON with the path and the callback
Upvotes: 1
Views: 40
Reputation: 1073978
To call a function when the link is clicked, use the click
event rather than trying to generate JavaScript source with the arguments in it to put on the href
:
$("#subjectBtns").append(
$('<a href="javascript:;" class="btn btn-mghg"></a>')
.click(generateSubjectOverview.bind(null, data["themen"]["themen"][i]["dateiName"]))
.append(data["themen"]["themen"][i]["name"])
);
This bit:
generateSubjectOverview.bind(null, data["themen"]["themen"][i]["dateiName"])
...looks up the value from the data
object and binds that value to generateSubjectOverview
, setting up a click
handler to call the resulting bound function. The result is the same, but you don't make an unnecessary round-trip through JavaScript source code, so this works not just for strings and numbers, but any kind of argument you may want to pass.
Note: Function#bind
is an ES5 feature. If you still need to support really old browsers (IE8, for instance), it can be shimmed. Search for "Function bind shim" to find options.
Upvotes: 2
Reputation: 4798
You have a problem with '
and "
. change this
$("#subjectBtns").append('<a href="javascript:generateSubjectOverview("' + data["themen"]["themen"][i]["dateiName"] + '");" class="btn btn-mghg">' + data["themen"]["themen"][i]["name"] + '</a>');
to this
$("#subjectBtns").append('<a href="javascript:generateSubjectOverview(\"' + data["themen"]["themen"][i]["dateiName"] + '\");" class="btn btn-mghg">' + data["themen"]["themen"][i]["name"] + '</a>');
Upvotes: 1