문제

I'm stuck with this problem:

<body onload="document.body.innerHTML="<script>alert('hi')</script>"">

The problem is that i cant use quotes within quotes within quotes. Any ideas?

도움이 되었습니까?

해결책

To represent a " character inside an HTML attribute delimited by " characters, use the entity &quot;

I'd recommend attaching event listeners using JavaScript rather then using intrinsic event attributes though. It simplifies things greatly.

Note however, that browsers will not execute JavaScript added to the document with innerHTML. If you want to add a script programatically, the use createElement / appendChild et al.

다른 팁

<body onload='document.body.innerHTML="<script>alert(\"hi\")</script>"'>

or

<body onload="document.body.innerHTML='<script>alert(\'hi\')</script>'">

It does work, but the script doesn't get executed because it is added after the browser parsed your code.

Note that if you wanted quotes within quotes within quotes within quotes you would have done: <body onload="document.body.innerHTML='<script>alert(\'\\\'hi\\\'\')</script>'" >

What is really impossible (i think) without &quot; is putting " and ' in the alert.

You could use a combination of backticks(`), single quotes, and double quotes.

Code:

<body onload="document.body.innerHTML=`<script>alert('hi')</script>`">

Gah! First off, don't do it that way. :D

Something like:

<body></body>

<script>
    window.onload = function () {
        document.body.innerHTML = "<script>alert('hi')</script>";
    }
</script>

. . . would be better. Consider some JQuery solutions, as well.

Even that specific approach, I wouldn't recommend, but I suspect that you are simply testing out how to add content to the body of your HTML after the page is loaded, rather than actually wanting to use the alert(). ;) If that's the case, try something like this:

<body></body>

<script>
    window.onload = function () {
        document.body.innerHTML = "some text";
        alert('hi'); // if you really want to test that the JS is working after load.
    }
</script>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top