javascript How to dynamically generate the code in the JS file (script tag) based on the dynamically generated string
三叔
三叔 2017-06-12 09:29:03
0
2
756

My code is as follows

    Title  

test

test2

I don’t want to get the value of each P, just as an analogy. I want to know how to dynamically render the code inside

When there are three .name p

test

test2

test3

Then the final code in

How can we achieve this effect?

三叔
三叔

reply all (2)
阿神

Do you want the return result in fun1() to be used as the execution js statement? ? You can use eval() to execute

    三叔

    You can directly define fun1 to return the text of the specifiedclassNameDOM, and then just run it directly. Anyway, when you generate code, you want to execute it immediately.

    function func1(className) { return $(className).find("p").text(); } for (var i = 0; i < $(".name").length; i++) { console.log(`name${i} p:`, func1(`.name${i}`)); }

    You don’t need to dynamically generate scripts, the script itself is very flexible. The code below is equivalent to the one you want to generate

    var textArray = $(".name p") .map(function() { return $(this).text() }).toArray();

    If you want to loop through each.name pyou can directly

    $(".name p") .each(function() { $p = $(this); // .... })

    If you want to process the specified name, you can

    // ES6 语法,若需要可转换为 es5 的 var textArray = ["name1", "name2", "namen"] .map(name => $(`.${name}`)) .map($name => $name.children("p").text()); // 这里本来就是原生数组,不需要 toArray()

    So what you want to do must be handled by dynamically generated scripts? If it is really needed, this is usually done by the server, not the front end. If the front-end can generate a script to run, it can definitely run a certain piece of code directly...

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!