如何使外部文件中的javascript只在PHP文件中div中的图像上工作?

如何使外部文件中的javascript只在PHP文件中div中的图像上工作?,javascript,jquery,image,Javascript,Jquery,Image,我对网络开发还很陌生,我在不断学习 我有一个PHP文件index.PHP,其代码类似于下面的代码,div在styles.css中定义: <div class='imgBox' id='imgBox'> <form name='graphForm' id='graphForm' method='post' action='/'> <input type='image' id='clicked' src='" . WebPath. "/image

我对网络开发还很陌生,我在不断学习

我有一个PHP文件index.PHP,其代码类似于下面的代码,div在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>
我有一个外部js文件showCoords.js,其代码如下:

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;
            }); 
    });
目前,我将showCoords.js文件放在头文件header.html中:

<script type='text/javascript' src="http://blahblah.org/files/showCoords.js"></script>
我的理解是,我觉得这个特定的js应该在网页本身加载之后加载,然后在该分区的图像上自动运行。这是错误的吗

当我加载页面时,没有发生任何事情,因此我非常感谢任何帮助


编辑:在Firebug中,我得到一个引用错误:showCoords未定义错误。这是否意味着showCoords.js甚至没有被包括在第一位?

您的jQuery选择器是错误的。尝试使用$'.clickableImage'并从那里开始调试。

您需要等到文档准备就绪后才能启动所有代码,我们称之为domready或javascript中的documentready

要在jQuery中执行此操作,请使用以下命令:

$(function() {
   // insert all your code here
});
您还试图选择一个名为clickable image的元素。您可能希望找到@oxo提到的类

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

如果您使用的是jQuery,那么您使用的选择器的方式是错误的

$应为$'工具提示'


$'clickableImage'应该是$'。clickableImage'

按照您的建议进行了更改,但我看不出有什么不同。我不确定我是否理解。你是说js文件中的所有内容都应该在内部运行?这个代码段$'.clickableimage'将在哪里选择live?是的,在dom准备就绪之前,不应运行任何代码。$'clickableImage不是选择器,您需要指定类或idOk,但在上面的PHP代码中,我确实指定了clickableImage作为类,clicked作为id,并在js代码中使用了它。是的,jquery使用css选择器,所以使用。clickableImage而不是clickableImage-注意周期啊,这很有意义。我注意到在Firebug中,我得到了一个ReferenceError:showcoords不是定义错误。也许这就是问题所在?