2
@Scripts.Render("~/bundles/jquery", "~/bundles/jqueryui", "~/bundles/WorkbenchScripts")
@Styles.Render("~/Content/WorkbenchCss")
<script type="text/javascript">

    $(document).ready(function () {
        checkSpecialChars('#txtCreateSet');
        $('#btnCancelSet').click(function (e) {
            window.close();
        });
    });


    //this function is used to allow only specific characters in function
    function checkSpecialChars(textboxID) {
        debugger;

        return textboxID.each
            (
                function () {
                    var allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    allowedChars += "abcdefghijklmnopqrstuvwxyz";
                    allowedChars += "0123456789";
                    allowedChars += " "; //Space
                    //Check if try to specifying allowed special characters for Name fields
                    allowedChars += "-_";
                    //on keypress
                    $(textboxID).keypress(function (e) {
                        var keyUniCode = !e.charCode ? e.which : e.charCode;

                        var charValue = String.fromCharCode(keyUniCode);

                        if (keyUniCode != 13) {
                            if (allowedChars.indexOf(charValue) == -1)
                                e.preventDefault();
                        }
                    });
                    //On paste
                    $(textboxID).bind('paste', function (e) {
                        setTimeout(function () {
                            var newText = textboxID.val();
                            $.each(newText, function (i) {
                                if (allowedChars.indexOf(newText.charAt(i)) == -1)
                                { textboxID.val(textboxID.val().replace(newText.charAt(i), '')); }
                            });
                        }, 1);
                    });
                }
            );
            };
</script>






<table>
        <tr>
            <td>
              @Html.Label("Create Set")
            </td>
            <td>
             @Html.TextBoxFor(model => model.SetName, new { id = "txtCreateSet" })
            </td>
        </tr>
<table>

在上面的代码中,我收到错误“对象不支持此属性”,我使用的是 MVC4,在这里我在 mvc 视图中编写了代码,在文本框中只允许使用 0-9 az AZ - _ 和空格字符.我在哪里做错了?谁能帮我得到想要的解决方案?

4

1 回答 1

6

那是因为您将选择器字符串而不是对象传递给您的函数。

看这里:

checkSpecialChars('#txtCreateSet');

这意味着当您执行以下操作时,您将收到该错误,因为each字符串上没有方法:

return textboxID.each

试试这个,传递 jQuery 对象:

checkSpecialChars($('#txtCreateSet'));
于 2013-05-23T14:38:44.173 回答