这是我运行的简单代码,希望能够控制 html5 验证,但浏览器显示 setCustomvalidity
不是函数。我做错了什么?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<input type='text' id='tocheck' />
<script>
$("#tocheck").click(function () {
var $this = $(this);
$this.setCustomValidity("slkdjf");
});
</script>
</body>
</html>
最佳答案
jQuery 没有 setCustomValidity
函数,但实际的 DOM 元素有。 jQuery 选择器总是返回一个数组,因此您可以使用零索引来获取实际的 DOM 元素,或者您可以只使用 this
(而不是 $(this)
)来获取您可以在其上设置自定义有效性的 DOM 元素。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<form>
<input type='text' id='tocheck'/>
<button>
Submit
</button>
</form>
<script>
$("#tocheck").click(function(){
this.setCustomValidity("slkdjf");
});
</script>
</body>
关于javascript - setCustomValidity 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582227/