我可能会在这里弄错,但我认为内联html可以使用onmouseover调用外部javascript文件的函数。
例如:
<a href="#" onmouseover="updateParentImage('<?php echo $this->getGalleryUrl($_image) ?>');">
我的EXTERNAL jquery / javascript文件函数如下所示:
function updateParentImage ($image_url)
{
alert($image_url);
$('.product-img-box .product-image img').attr('src', $image_url);
}
该功能永远不会运行。我完全错过了什么吗?即使javascript是外部的,该标签也不应该调用相应的文件吗?
注意:如果我将javascript包含在内,则会显示警告框,但我尝试在文档中更改的图像不会更改,即使我在代码中使用相同的引用作为其中的另一个位置更新图像。
任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
这样的事情怎么样......
<a href="#" class="imageChanger" data-imagesrc="<?php echo $this->getGalleryUrl($_image) ?>">
然后使用jquery添加mouseenter事件
$(document).ready(function(){
$('.imageChanger').mouseenter(function(){
alert($image_url);
$('.product-img-box .product-image img').attr('src', $(this).data('imagesrc'));
});
});
答案 1 :(得分:1)
根据您的评论,我找到了可能对您有帮助的解决方案:
<a href="#" data-imageurl="<?php echo $this->getGalleryUrl($_image) ?>">This is one of many links</a>
然后你可以在你的脚本中使用它:
(function($) {
$(document).ready(function() {
$('a').hover(function() {
// this happens onmouseenter
var imageUrl = $(this).data('imageurl');
updateParentImage(imageUrl);
}, function() {
//this happens onmouseleave
});
});
function updateParentImage(image_url) {
alert(image_url);
$('.product-img-box .product-image img').attr('src', $image_url);
}
})(jQuery);
这一小段代码绑定到所有'a'元素,在你的情况下可能不完全正确,但它只是作为一个例子。然后我将所有代码包装在一个闭包/立即调用的函数表达式(IIFE)中,以确保我们不会过多地污染全局命名空间。它还确保$在该闭包内保留jQuery。
还有一点需要注意的是,我在链接上使用了data属性来存储该链接的图像URL。干净又简单:)
如果您有任何疑问,请大声喊出来!
答案 2 :(得分:1)
(参见上面的评论,了解回应的背景)
你永远不应该复制事件绑定,并且永远不要回答内联的,突兀的JavaScript。
绑定一次并将您的网址设置为您可以抓取的属性。此外,我假设您不想触摸外部JS函数,我写下以下内容:
<div id="linkContainer">
<a href="#" data-imgsrc="<?php echo $this->getGalleryUrl($_image) ?>">Something</a>
</div>
JavaScript(如果必须,可以在脚本标记中放入页面的HTML中):
$('#linkContainer a').bind('mouseover', function() {
updateParentImage($(this).data('imgsrc'));
return false;
});