函数未在javascript中定义。为什么?

时间:2013-08-14 18:08:50

标签: javascript jquery html

我从html调用javascript函数。但它保留了返回错误并且在jsfiddle中没有定义函数。

这里是html代码

<div id="Container">
    <img alt="Click to zoom" class="image" onclick="resizeImg(this)" 
src="http://www.extremetech.com/wp-content/uploads/2012/12/Audi-A1.jpg" />
</div>

这里是javascript

function resizeImg (img) {
        var resize = 150; // resize amount in percentage
        var origH  = 61;  // original image height
        var origW  = 250; // original image width
        var mouseX = event.x;
        var mouseY = event.y;
        var newH   = origH * (resize / 100);
        var newW   = origW * (resize / 100);

        // Set the new width and height
        img.style.height = newH;
        img.style.width  = newW;

        var c = img.parentNode;

        // Work out the new center
        c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
        c.scrollTop  = (mouseY * (resize / 100)) - (newH / 2) / 2;
    }

为什么以及如何解决它?

2 个答案:

答案 0 :(得分:4)

您需要在左侧面板的第二个下拉列表中选择no-wrap in body/head

因为您选择了onDomReady,所以您的脚本被$(function(){...})包围 前

<script type="text/javascript">//<![CDATA[ 
$(function(){
function resizeImg (img) {
    var resize = 150; // resize amount in percentage
    var origH  = 61;  // original image height
    var origW  = 250; // original image width
    var mouseX = event.x;
    var mouseY = event.y;
    var newH   = origH * (resize / 100);
    var newW   = origW * (resize / 100);

    // Set the new width and height
    img.style.height = newH;
    img.style.width  = newW;

    var c = img.parentNode;

    // Work out the new center
    c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
    c.scrollTop  = (mouseY * (resize / 100)) - (newH / 2) / 2;
}

});//]]>  

</script>

这使得匿名函数的本地函数resizeImg传递给$(),因此它对全局范围不可见。单击图像时,将在全局范围内搜索该方法,其中不可见的是错误原因

答案 1 :(得分:1)

你没有在新的高度和宽度中指定“px”,而在jsfiddle中你必须将它包装在头部

function resizeImg (img) {
    var resize = 150; // resize amount in percentage
    var origH  = 61;  // original image height
    var origW  = 250; // original image width
    var mouseX = event.x;
    var mouseY = event.y;
    var newH   = origH * (resize / 100);
    var newW   = origW * (resize / 100);

    // Set the new width and height
    img.style.height = newH+"px";   // changes made
    img.style.width  = newW+"px";

    var c = img.parentNode;

    // Work out the new center
    c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
    c.scrollTop  = (mouseY * (resize / 100)) - (newH / 2) / 2;
}

工作jsfiddle Demo

希望这有助于谢谢