我有一個在ids(:, - ,_)中使用特殊字符的HTML表單。該表單使用JQuery驗證插件來驗證用戶輸入。具體的ID包括一個GUID, 以下是示例代碼:如何在jQuery驗證中處理html元素id/name中的特殊字符?
<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-validate/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#respondForm').validate({ onclick: false,
onkeyup: false,
onfocusout: false,
highlight:
function(element, errorClass) {
$(element).css({ backgroundColor: '#FFFF88' });
}
,
errorLabelContainer: $("ul", $('div.error-container')),
wrapper: 'li',
rules: { Input:_CDD66FA6-D190-434D-AF51-8272F64E0646_14ecbb3f-c0e0-4caf-b03a-013d12118405:
{
required: true
, minlength: 5
, maxlength: 10
}
}
,
messages: { firstName:
{
required: "xxx_Required"
, minlength: "XXX Should be greater than 5"
, maxlength: "XXX Cannot be greater than 10"
}
}
});
});
</script>
</head>
<body>
<form action="/Home/Submit" method="post" id="respondForm">
<div>
<div class="error-container">
<ul>
</ul>
</div>
</div>
<div>
<input type="text" id="Input:_CDD66FA6-D190-434D-AF51-8272F64E0646_14ecbb3f-c0e0-4caf-b03a-013d12118405" name="Input:_CDD66FA6-D190-434D-AF51-8272F64E0646_14ecbb3f-c0e0-4caf-b03a-013d12118405" />
<br />
<input type="submit" name="submit" value="Submit" />
<br />
</div>
</form>
正如你可以看到輸入型文本元素具有ID /名稱爲「Input:_CDD66FA6-D190-434D-AF51-8272F64E0646_14ecbb3f-c0e0-4caf-b03a-013d12118405
」
如果我運行在瀏覽器中此頁,我收到一個JavaScript錯誤:
Webpage error details
Message: Expected '}'
Line: 23
Char: 50
Code: 0
URI: http://localhost:64603/
錯誤指向這一行:
function(element, errorClass) {
$(element).css({ backgroundColor: '#FFFF88' });
}
,
errorLabelContainer: $("ul", $('div.error-container')),
wrapper: 'li',
***[Line 23] -----> rules: { Input:_CDD66FA6-D190-434D-AF51-8272F64E0646_14ecbb3f-c0e0-4caf-b03a-013d12118405:***
我該如何解決?
總結您的ID在引號(在JavaScript)。 – 2009-11-10 07:55:43
另外,請注意,這不是ID,而是您在此處使用的NAME屬性。 – 2009-11-10 10:23:22