0

我试图在 simplecart 中的项目上添加错误参数时收到警报。当该字段为空或低于 400 或高于 500 时。

一切正常,但当字段为空时不会发出警报。

html:

<input required max="500" min="400" type="number"  class="item_width">

JavaScript:

<script>
simpleCart.bind( 'beforeAdd' , function( item ){
if( item.get( 'width' ) < '400' 
|| item.get( 'width' ) > '500' 
|| item.get( 'width' ) === 'null')
{ 
alert("Choose between 400 and 500");
return false; 
}
});
</script>
4

2 回答 2

0

尝试这个,

 if( item.get( 'width' ) < '400' || item.get( 'width' ) > '500' || item.get( 'width' ) === 'null' || item.get( 'width' ) === '')
  {   alert("Choose between 400 and 500");   }
于 2014-08-05T16:05:25.870 回答
0

我不知道 simplecart 如何处理空字符串,但是您写了'null',这意味着输入的文本需要是"null"字符串,而不是对象null。另外,一个空字符串不是空的,它是一个空字符串,所以试试:

simpleCart.bind( 'beforeAdd' , function( item ){
if ( item.get( 'width' ) < '400' 
|| item.get( 'width' ) > '500'
|| item.get( 'width' ) == null
|| item.get( 'width' ) === '')
{ 
alert("Choose between 400 and 500");
return false; 
}
});

<此外,通过或>针对 a测试整数string并不是好的编程。它可能有效,但请正确编码:

simpleCart.bind( 'beforeAdd' , function( item ){
if ( item.get( 'width' ) < 400
|| item.get( 'width' ) > 500
|| item.get( 'width' ) == null
|| item.get( 'width' ) === '')
{ 
alert("Choose between 400 and 500");
return false; 
}
});

为了确保 item.get( 'width' ) 实际上给你一个整数,你应该解析它们:

...
parseInt( item.get('width') ) < ...
...
于 2014-08-05T15:51:15.467 回答