简体   繁体   中英

How could I make it such that javascript in an external file works only on an image in a div inside a PHP file?

I'm pretty new to web development, and am learning as I go along.

I have a PHP file (index.php) with code similar to that below (divs are defined in styles.css):

<div class='imgBox' id='imgBox'>
    <form name='graphForm' id='graphForm' method='post' action='/'>
        <input type='image' id='clicked' src='" . WebPath. "/images/graph.png' class='clickableImage' />
        <input name='x_y' id='x_y' type='hidden'/>
        <input name='p_id' id='p_id' type='hidden' value='".$RecordID."'/>          
    </form>
</div>

I've an external js file (showCoords.js) with the following code:

var tooltip = $( '<div id="tooltip">' ).appendTo( 'body' )[0];

$( 'clickableImage' ).
    each(function () {
        var pos = $( this ).position(),
            top = pos.top,
            left = pos.left,
            width = $( this ).width(),
            height = $( this ).height();

        $( this ).
            mousemove(function ( e ) {
                var x = some_code_here,
                    y = some_code_here;

                $( tooltip ).text( x + ', ' + y ).css({
                    left: some_code_here,
                    top: some_code_here
                }).show();
            }).
            mouseleave(function () {
                //somestuff;
            }); 
    });

I currently have it such that I placed the showCoords.js file in the header file (header.html):

<script type='text/javascript' src="http://blahblah.org/files/showCoords.js"></script>

My understanding is that I felt that this particular js should be loaded after the web page itself is loaded, and will then run automatically on the image in that div. Is this wrong?

Nothing is happening when I load the page, so I'd appreciate any help.

EDIT: In Firebug, I get a "ReferenceError: showCoords is not defined" error. Does this mean that showCoords.js is not even being included in the first place?

Your jQuery selector is wrong. Try using $( '.clickableImage' ) and start your debugging from there.

You need to wait until the document is ready before you fire all that code, we call it domready or documentready in javascript.

To do this in jQuery use this:

$(function() {
   // insert all your code here
});

You also are trying to select an element called clickable image. You probably want to find a class as @oxo has mentioned.

$('.clickableimage') would select <img class="clickabelimage" src="..." />

If you are using jQuery, you are using the wrong way of selector.

$( '<div id="tooltip">' ) should be $('#tooltip')

$( 'clickableImage' ) should be $('.clickableImage')

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