jQuery - 无法将类添加到动态添加到DOM的元素

时间:2013-05-28 13:50:40

标签: jquery jquery-on

我有一个AJAX请求返回的以下标记:

<form id="quotation-form" name="quotation-form" action="" method="POST">
    <label for="site-name">Site Name:</label>
    <input type="text" id="site-name" name="site-name" />

    <label for="postcode">Site Postcode:</label>
    <input type="text" id="postcode" name="postcode" />

    <label for="bandwidth-requirement">Bandwidth Requirement:</label>
    <select id="bandwidth-requirement" id="bandwidth-requirement">
       <option value="10" selected>10Mb</option>
       <option value="20">20Mb</option>
       <option value="30">30Mb</option>
    </select>

    <input type="submit" name="quotation-form-submit" id="quotation-form-submit" value="Get Quotation" />

</form>

的jQuery

$(document).on("submit", "#quotation-form", function() {
    // cache form input id's
    var site_name             = $('#site-name');
    var postcode              = $('#postcode');
    var bandwidth_requirement = $('#bandwidth-requirement');

    var valid = 1;

    // validate form input values
    if (site_name.val() == '') {
        name.addClass('error');
        valid = 0;
     } else {
         site_name.removeClass('error');
     }

     if (postcode.val() == '' || !checkPostcode(postcode.val())) {
         postcode.addClass('error');
         valid = 0;
     } else {
         postcode.removeClass('error');
     }

     if (bandwidth_requirement.val() == '') {
         bandwidth_requirement.addClass('error');
         valid = 0;
     } else {
         bandwidth_requirement.removeClass('error');
     }

});

错误是:

Uncaught TypeError: Object has no method 'addClass'

我在添加此验证之前尝试了一个警报,它运行正常,因此不确定问题是什么。

1 个答案:

答案 0 :(得分:1)

在此范围内,您似乎没有声明name var。

您是否在此范围之外宣布了它?我相信你可能想要:

if (site_name.val() == '') {
    site_name.addClass('error');
    valid = 0;
} else {
     site_name.removeClass('error');
}

您是否已逐步使用调试器?它可能会显示name为空......