问题描述:

This isn't something I really want to do, just wondering if it's possible.

Say I have a page like this, which is just a heading and an input box.

<!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>2014-4-24-01</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script>

function jQuerySetup() {

if($) {

$(document).ready( function () {

$("body").on("keypress", "input", function ( event ){

if(event.keyCode == 13){

$("body").get(0).innerHTML = this.value;

}

});

});

} else {

window.setTimeout(jQuerySetup, 250);

}

}

jQuerySetup();

</script>

</head>

<body>

<h3>Test</h3>

<input type="text" width="20">

<div id="testDiv"></div>

</body>

</html>

If I type the following into the input box and hit enter, nothing happens. Why is that?

<script>window.setTimeout(function () { alert("Uh oh"); }, 1000);</script>

EDIT: And I know that it's very easy for someone to run JavaScript through the console window and achieve a similar effect. But my question is more of understanding why the above isn't possible (or why I'm not getting it right).

网友答案:

It is possible to run script from an input box using eval(). The way you are doing it won't work since the specification states that scripts inserted via .innerHTML should not be executed (it's a large green note at the end of the section).

网友答案:

innerHTML won't execute the script, use jQuery html instead.

$("body").html(this.value);
网友答案:

From the w3c spec...

Note: script elements inserted using innerHTML do not execute when they are inserted.

Instead just use eval

网友答案:

You don't need if($) { and setTimeout because it's handled by $(document).ready.

You can try that:

<script>
$(document).ready( function () {
    $("body").on("keypress", "input", function ( event ){
        if(event.keyCode == 13){
            $("body").get(0).innerHTML = this.value;   
        } 
    });    
});
</script>

Working example here

相关阅读:
Top