我找到了以下JQUERY脚本来执行此操作:
$(document).ready(function(){
$('textarea').on('keypress', function(e) {
var val = $('textarea').val();
var validaterror = document.getElementById('errorvalidate');
if (e.which == 13) {
if(! /\S/.test(val)) {
validaterror.textContent = 'Please enter domain names in the field.';
return false;
}
validaterror.textContent = '';
}
});
});
但我不想在我的网站上使用Jquery,因为我对页面速度有一种痴迷,这是我网站上使用Jquery的单个脚本,并希望将该jquery转换为Javascript。请帮我解决这个问题。
答案 0 :(得分:3)
试试这个,
<强> SCRIPT 强>
document.getElementById('textId').onkeypress = function (e) {
var val = this.value;
var validaterror = document.getElementById('errorvalidate');
if (e.which == 13) {
if (!/\S/.test(val)) {
validaterror.innerHTML = 'Please enter domain names in the field.';
return false;
}
validaterror.innerHTML = '';
}
}
<强> HTML 强>
<textarea id="textId"></textarea>
<div id='errorvalidate'></div>
答案 1 :(得分:2)
首先处理事件
var handleEvent = function(_obj, _execute, _eventName) {
// Check for browser support of event handling capability
if (_obj.addEventListener)
_obj.addEventListener(_eventName, _execute, false);
else if (_obj.attachEvent)
_obj.attachEvent('on'+_eventName, _execute);
else
_obj['on'+_eventName] = _execute;
}
验证内容
var validate = function (){
var obj = document.getElementById('textarea');
var val = obj.value;
var validaterror = document.getElementById('errorvalidate');
if (e.which == 13) {
if(! /\S/.test(val)) {
validaterror.textContent = 'Please enter domain names in the field.';
return false;
}
validaterror.textContent = '';
}
}
把所有东西放在一起:
var textarea = document.getElementById('textarea');
handleEvent(textarea, validate, 'keypress');
答案 2 :(得分:1)
嗯,你可以一点一点地替换它:
$(document).ready(function(){
就像:
if (document.readyState === "complete") // jQuery uses an interval to check this.
和
$('textarea').on('keypress', function(e) {
就像:
document.getElementById("your_textarea").onkeydown = function(evt) {
// do what you like
};
和
$('textarea').val();
就像:
document.getElementsByTagname('textarea')[0].value // or give it an id and use getElementById
答案 3 :(得分:0)
尝试这样的事情
JAVASCRIPT
function validateMe(obj){
var val = obj.value;
var validaterror = document.getElementById('errorvalidate');
if (e.which == 13) {
if(! /\S/.test(val)) {
validaterror.textContent = 'Please enter domain names in the field.';
return false;
}
validaterror.textContent = '';
}
}
HTML CODE
<textarea rows="10" cols="5" onkeypress="validateMe(this)"></textarea>
答案 4 :(得分:0)
window.onload=function(){
document.getElementsByTagName('textarea').addEventListener('keypress', function(e) {
var val = document.getElementsByTagName('textarea').value;
var validaterror = document.getElementById('errorvalidate');
if (e.which == 13) {
if(! /\S/.test(val)) {
validaterror.textContent = 'Please enter domain names in the field.';
return false;
}
validaterror.textContent = '';
}
});
};