简体   繁体   中英

How to put an internal script inside a div tag?

I am trying to run a javascript inside of a div tag because i have heard its possible but for some reason the code does nothing.

<!DOCTYPE html>
<html>
<body>
<title>XDSITE</title>
<br>
<br>

<div id=mycode style="BACKGROUND: 
url('javascript:eval(window.alert("sometext"))'"></div>


</body>
</html>

You have some problems in your HTML it is not valid, you can't run JavaScript from a style attribute.

You can run Javascript from within a <script> tag which really is the best way to do it.

<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>

Alternatively there are some HTML elements that allow you to execute it on some events, like onchange , onclick etc.

<select onchange="myFunction()">

<button onclick="myFunction()">Click me</button>

https://www.w3schools.com/ is a great resource for learning more about each html element, and also JavaScript as a whole.

Good luck

can you please tell here which java script framework is you are using? you can achieve this by using and template java script framework like Angular, React... If u dont want to use any framework than you need to write pure javascript or jquery code for assigning the background css prop.

for entire body,

document.body.style.backgroundImage = "url('img_tree.png')";

for div,

document.getElementById("mycode").style.backgroundImage = "url('img_tree.png')";

 <!-- U have to give event inside expression like onclick ,mouseup Click that text --> <div id=mycode onclick="alert('Hi ....sometext')">THARA </div> 

<!DOCTYPE html> <html> <body> <title>XDSITE</title> <br> <br> <div id=mycode style="BACKGROUND: url('javascript:eval(window.alert("sometext"))'"></div> </body> </html>

Answer : Open script in footer

<script>
$( "#mycode" ).click(function() {

alert( "Hai" );

});
</script>

I hope its working for you ...

You can target HTML tag using getElementById() and then apply custom style like this document.getElementById("Mydiv").style.backgroundColor="#0000"

or apply a bunch of styles like this

var dev = document.getElementById("Mydiv");
dev.style.backgroundColor="#0000";
dev.style.fontSize="..";
dev.style.backgroundImage="..";

You can run your function using "onerror" event. And also you must do some error in that case. For eg.

<img src="someFakeSrc" onerror='javascript:eval(window.alert("sometext"))'>

HTML doesn't see a src of picture then run a 'onerror' event.

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