3

在 Google Chrome 上测试我的代码时出现问题,在 Firefox 上测试时我没有任何问题。我有一个函数,我在onblur事件中调用它。它在 Firefox 上运行良好,但谷歌浏览器在控制台上给了我这个错误

未捕获的 ReferenceError:未定义填充

HTML 代码:

<input type="text" name="title" id="title" placeholder="mytitle" onblur='fill(this);'>

JavaScript 代码:

function fill(element,value = false){
    if(element.value == ""){
        $("#"+element.id).css('border-color','red');
    }else{
        $("#"+element.id).css('border-color','#56de56');
    }
    if(value == true){
        if(element.value > 75 || element.value < 5)
            $("#"+element.id).css('border-color','red');
    }
}

我在该行之前和之后声明fill了函数,所以我面临同样的问题。

4

1 回答 1

3

EcmaScript, the standard JS is based on as of version 5.1 does not support optional parameters.

function fill(element,value = false){

Does not do what you expect it to. Instead, you have to do this manually:

function fill(element,value){
     if(typeof value === 'undefined') {
          value = false;
     }

Or in a shorter notion if you're only expecting boolean values

function fill(element,value){
    value = value || false;

Note - These both have cases they miss - as Fabrício Matté suggested in the comments you can also check arguments.length if you want to differenciate not getting an argument passed, and getting undefined explicitly although that's rarely the case.

although optional parameters are in the EcmaScript 6 proposal

(Firefox however, does independently support them even today)

于 2013-08-16T18:51:34.207 回答