Javascript 意外的号码错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26064043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:16:23  来源:igfitidea点击:

Unexpected Number error

javascripthtml

提问by user3723666

I have been writing a function to allow users to upload images from their local file system to a website using JavaScript. I have successfully been able to upload images to the browser.

我一直在编写一个函数,允许用户使用 JavaScript 将图像从本地文件系统上传到网站。我已经成功地能够将图像上传到浏览器。

I have also written a function to allow the user to delete these images.

我还编写了一个函数来允许用户删除这些图像。

var count = 0;
function getPhoto(){

    var file = document.getElementById('ad_photo');
    var list = document.getElementById('ad_photo_upload');
    var fReader = new FileReader();
    var photo_list = [];
    var counter;

    fReader.readAsDataURL(file.files[0]);
    fReader.onloadend = function(event){

        counter = count.toString();

        list.innerHTML += "<li id = 'pic " + counter + "'><img src='" + event.target.result + "'></img><a class = 'close' onclick = 'rem_pic(pic " + counter + ")'>X</a></li>"; 
        photo_list[count] = event.target.result;
        count++;

    }



}

function rem_pic(theID){

    var element = document.getElementById(theID);
    element.outerHTML = "";
    delete element;

}

My issue is whenever I call the "rem_pic(theID)" function I get a Chrome Browser error message that says "Uncaught SyntaxError: Unexpected number". Does anyone have any clue to why this might be? And how I could possibly improve the functions I have written so they work correctly?

我的问题是,每当我调用“rem_pic(theID)”函数时,我都会收到一条 Chrome 浏览器错误消息,上面写着“Uncaught SyntaxError: Unexpected number”。有没有人知道为什么会这样?我如何才能改进我编写的函数,使它们正常工作?

Thanks

谢谢

回答by antyrat

This happens because you pass a number to your function:

发生这种情况是因为您向函数传递了一个数字:

'rem_pic(pic " + counter + ")'

will render to

将呈现为

'rem_pic(pic 1)'
             ^ or any other number according to your counter value

And this is wrong as javascript params can't contain spaces.

这是错误的,因为 javascript 参数不能包含空格。

So you probably need to pass a string:

所以你可能需要传递一个字符串:

rem_pic(\"pic " + counter + "\")

Looking at your code seems like you use it's as HTML idattribute. idattribute can't contain space chars too so your code should be like

查看您的代码似乎您将其用作 HTMLid属性。id属性也不能包含空格字符,所以你的代码应该像

rem_pic(\"pic" + counter + "\")

if your idin layout has format id="pic1", id="pic2", etc.

如果您id在布局具有格式id="pic1"id="pic2"等等。