错误:未捕获的异常:[例外..."字符串包含...."

时间:2012-02-23 21:56:32

标签: javascript jquery string dom

我正在运行以下javascript:

$('img').each(
    function(){
        var w = parseInt(this.width);
            alert(w);
            alert(this.src);
        if(w > 300){

            var percent = parseInt((w/666)*100);
            $(this).removeAttr('width height').css('width',percent + "%");

        }
});

我收到以下错误:

  

错误:未捕获的异常:[异常...“字符串包含无效   字符“代码:”5“nsresult:”0x80530005   (NS_ERROR_DOM_INVALID_CHARACTER_ERR)“位置:   “http://code.jquery.com/jquery-1.6.4.min.js行:2”]

我实际上在尝试跟踪这个问题时遇到了麻烦,因为它不能很好地描述问题或问题的根源。任何人都可以对这个问题有所了解吗?

由于

3 个答案:

答案 0 :(得分:0)

$(\'img\')无效。应该是$('img')。还有一些其他地方你试图逃避单引号,但你不需要。您的代码看起来应该更像这样:

$('img').each(
    function(){
        var w = parseInt(this.width);
            alert(w);
            alert(this.src);
        if(w > 300){

            var percent = parseInt((w/666)*100);
            $(this).removeAttr('width height').css('width',percent + "px");

        }
});

答案 1 :(得分:0)

看起来你不知道正确的语法。 试试这个:

$('img').each(
    function(){
        var w = parseInt(this.width);
            alert(w);
            alert(this.src);
        if(w > 300){

            var percent = parseInt((w/666)*100);
            $(this).removeAttr('width height').css('width',percent + "px");

        }
});

答案 2 :(得分:0)

对我来说看起来像is running perfectly - 虽然它不会改变图像的大小 - 所以问题可能在你的代码/页面的其他地方。

关于代码中的逻辑,我不确定你在这里要做什么;

parseInt((W/666)*100)

您是否尝试将所有照片设为宽度最大尺寸?即在浏览器中缩小图片的尺寸? If so, why not just set the size to a fixed value,像;

$('img').each(
    function(){
        var maxwidth = 300;
        var w = parseInt(this.width);
        var h = parseInt(this.height)
        if(w > maxwidth){
            var hscale = parseInt(h/(w/maxwidth));
            $(this).width(maxwidth).height(hscale);
        }
});