简体   繁体   English

Jquery用每个修改html

[英]Jquery modify html with each

I have a problem with jQuery. 我有一个jQuery的问题。 I want to write a function that dynamically replaces some content in my HTML. 我想编写一个动态替换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: 我在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. 首先,不要遍历文档中的每个元素,然后使用if()语句。 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: 以下示例应该实现您正在尝试执行的操作,而不需要使用邪恶的eval()函数:

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);
       }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM