简体   繁体   中英

How can I pass an html img element to a javascript included file?

This is a question from a noob in javascript. I tried to find something similar the last two days but I didn't find. I try to pass an html image element to an external javascript file which I include to the rest html code. The javascript fade in and fade out an image. Because I want to use different images everytime, thus I want to have a function in an external javascript file.

What I did so far:

PHP and HTML:

<?php
if ($success){
echo"<link rel='stylesheet' href='js/jquery-ui-1.11.4-smoothness.css'>
                <script src='js/jquery-1.11.3.js'></script>
                <script src='js/jquery-ui-1.11.4.js'></script>

            <img id='tick' src='tick.png'>

            <script type='text/javascript' src='js/success_failure_signs.js'>
            success_failure(tick);
            </script>";

}?>

Javascript file has this code:

function success_failure(tick){
    var x = tick; 
    x.fadeIn();
    x.fadeOut(1000);
    }

The browser's console doesn't give any error. It seems that the function success_failure doesn't get the image. What is wrong on this code and how can I fix it? Thank you in advance!

maybe passing the image to the script is the wrong way of thinking here. Most of the time with Javascript for web pages the JS gets the image from the HTML site itself.
You are already including jQuery so look into how to get an element from the page with jQuery .

You haven't defined tick when you make your function call. Try this...

<script type="text/javascript" src="js/success_failure_signs.js">
</script>

<script type="text/javascript">
  var tick = $("#tick"); 
  success_failure(tick);
</script>

EDIT: I've also separated the inclusion of the script and your code to call it into two separate script tags.

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