开发者

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 s开发者_Python百科howCoords.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?


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="..." />


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


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

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜