简体   繁体   中英

javascript that produces functioning javascript

can you write javascript that produces/writes/etc. functioning javascript?

for example, have a link that has a function tied to it that when clicked produces a functioning javascipt snippet? The snippet could deal with a completely other elements.

For example

Link #1(has the javascript function that produces javascript) Link #2(does absolutely nothing for now)

Click on link #1(produces javascript snipped that says "when link #2 is clicked document.write('hello')"

Clicking on link #2 now produces "hello" whereas it previously did nothing. Is that possible?

Yes, you can dynamically assign event handlers described in text.

However, dynamic code generation is far more difficult than it sounds unless you're just following basic patters and replacing certain variables. Writing programs that write programs has long been a fascination of the computer industry, and this gave way to functional programming, which can be done in javascript .

Create the input/delete keys on the onClick handler for the datepicker, you can attach date information (or other data) when the input(s) are created. Now, you should look into $.delegate() for how to bind handlers to those inputs created. $.delegate can bind handlers to elements that are not created yet, so when they are created they will fire a handler. By storing date relevant information in the inputs via $.data() or data- attributes you will have context aware handlers for dealing with things.

If I understand your question correctly, you could do what you want with the code below.

Not sure why you'd want to do this, though.

can you write javascript that produces/writes/etc. functioning javascript?

You can do this the way I did it, or by using eval -- though, as many coders have pointed out, eval is evil!

<html>

<head>

<script type="text/javascript">

function initLinks(){
    document.getElementById("link1").addEventListener("click", function(){
        document.getElementById("link2").addEventListener("click", function(){
            document.write("hello");
        }, false);
    }, false);
}
</script>


</head>

<body onload="initLinks()">

<a id="link1">Link 1</a>
<a id="link2">Link 2</a>

</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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