我对 Web 开发还很陌生,并且正在不断学习。
我有一个 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应该在网页本身加载之后加载,然后会在该div中的图像上自动运行。这是错误的吗?
加载页面时没有任何反应,因此非常感谢您的帮助。
编辑:在 Firebug 中,我收到“ReferenceError:showCoords 未定义”错误。这是否意味着 showCoords.js 根本就没有被包含在内?
最佳答案
您需要等到文档准备好才能触发所有代码,我们在 JavaScript 中将其称为 domready 或 documentready。
要在 jQuery 中执行此操作,请使用以下命令:
$(function() {
// insert all your code here
});
您还尝试选择一个名为可点击图像的元素。您可能想找到 @oxo 提到的一个类。
$('.clickableimage') would select <img class="clickabelimage" src="..." />
关于javascript - 我如何才能使外部文件中的 javascript 仅适用于 PHP 文件内的 div 中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7452812/