简体   繁体   中英

Can I just put my javascript right next to my <div>

If I have some javascript/jQuery acting on a particular div inside tags (for an animation), can I just put the javascript (in a src="link-to-my-js.js" file) right next to my div?

I mean something like the following:

<body>
<div id="special">Some html</div>
<script type="text/javascript">javascript related to my div tag above...</script>
</body>

whereever you add your code wrap it with document .ready.

It will wait till all the dom is ready, so you will be safe.

<script type="text/javascript">
$(document).ready(function() {

 });
</script>

You can put them anywhere you want, but

You can add the tag anywhere you please. Remember though that if your script tries to act on an element that has not yet been loaded it will fail.

So if your load your script tag before your div and the script isn't activated by an onload event or something similar element will not be found.

On the contrary if the tag appears after the element you can manipulate it as normal.

It does not matter where you put it if you wrap your code with the $(function(){/*code here*/})

reference: http://api.jquery.com/jquery/#jQuery3

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