【问题标题】:Uncaught TypeError: Cannot read property 'match' of undefined未捕获的类型错误:无法读取未定义的属性“匹配”
【发布时间】:2014-06-14 09:55:18
【问题描述】:

使用这段 jQuery,我检查某些字段是否匹配或不为空,但出现此错误。

未捕获的类型错误:无法读取未定义的属性“匹配”

谁能告诉我我在这里做错了什么?

if ( width.match( /^\d+$/ ) && height.match( /^\d+$/ ) && type.length > 0 && color.length > 0 ) {

这是完整的代码:

if( $( "#config" ) ) {
        $( 'input, select' ).on( 'change', function(){
            var width   = $( "#config-steps #width" ).val();
            var height  = $( "#config-steps #height" ).val();
            var type    = $( "#config-steps #type" ).val();
            var color   = $( "#config-steps #selected-color" ).val();

            if ( width.match( /^\d+$/ ) && height.match( /^\d+$/ ) && type.length > 0 && color.length > 0 ) {
                $( "#checkout-message" ).show();

                // Change visible price 
                $( "#change-price" ).html( calculate_price().toFixed( 2 ) );

            } else {
                return false;
            }

        });
    }

【问题讨论】:

  • 尝试删除变量声明后的空格。
  • 您的一个或多个变量未定义。你确定你的选择器是好的吗?
  • if( $( "#config" ) ) 在 jQuery 中总是如此!
  • @epascarello 哦,好吧。那我怎样才能以正确的方式检查呢?
  • 表示#width#height 或两者均未找到或不是#config-steps 的后代。

标签: javascript jquery regex match


【解决方案1】:
if( $( "#config" ) ) {

对 jQuery 来说总是正确的,因为 jQuery 返回一个对象并且对象是真实的。检查应该检查将返回数字的长度,零为假。

if ($("#config").length) {

现在当 jQuery 没有找到元素时,val() 会返回 undefined,所以它没有找到元素。

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 2021-12-22
    • 2015-01-06
    • 2017-07-26
    • 1970-01-01
    • 2019-02-26
    相关资源
    最近更新 更多