I have a problem with jQuery. I want to write a function that dynamically replaces some content in my HTML.
This is the function:
function renderPage(datas, html) {
$(html).find("*").each(function(){
if ($(this).attr("data-func")) {
var df = $(this).attr("data-func");
var content = null;
eval("content = " + df + "($(this),datas);");
console.log(content);
}
});
}
The problem is, that it has no effect! I see in the log that the content variable is right, but the output is not different.
My function in eval:
function fill(element,data) {
element.html("BASSZA MEG");
var events = data.events;
var i = 0;
var n = events.length;
for (;i<n; i++) {
obj = events[i];
var tr = $("<tr>");
var nev = $("<td>");
var link = $("<a href='programbelso.html#id="+obj["event_id"]+"&logo="+obj["event_logo"]+"'>");
link.html(obj["event_name"]);
nev.append(link);
tr.append(nev);
element.append(tr);
}
console.log("element: " + element);
return element;
}
Firstly, do NOT loop over every single element in the document, and then use an if() statement. You can drastically improve the performance by using the right selector.
The following sample should achieve what you're trying to do without needing to use the evil eval() function, too:
function renderPage(datas, html) {
$('[data-func]').each(function() {
var df = $(this).attr("data-func");
var the_func = window[$(this).attr("data-func")];
if(typeof the_func === 'function') {
var content = the_func($(this), datas);
console.log(content);
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With