我有一个脚本,让用户提交电子邮件。但是我想限制一些用户发布特定的世界,一旦使用该单词,就无法提交表单(返回false;)并输出警告。
那么如何在jQuery中进行单词检查?
示例:的
1)想要封锁的世界:披萨
2)用户将此单词放入textarea
3)用户点击提交,但他在其他单词旁边使用了这个词,所以表单不提交
如果jQuery不能这样做,但Javascript可以,那么我也欢迎使用Javascript解决方案。
答案 0 :(得分:2)
从概念上讲,当按下提交按钮时,您将获得textarea的内容。你会在它上面搜索一个单词pizza(一个简单的正则表达式)然后如果找到它,你会设置一个cookie,禁止他们提交一段时间(你决定多长时间)。然后,在提交按钮上,您将检查cookie是否存在,如果存在,则禁止提交功能。您可以使用jQuery或纯javascript /浏览器执行此操作 - 这是个人偏好。
以下是代码的一小部分:
var o = document.getElementById("myTextArea");
if (o.value.search(/\bPizza\b/i) != -1) {
alert("Pizza not allowed");
// set cookie preventing future access
}
答案 1 :(得分:1)
取回放置在表单中的文本字符串并对其执行indexOf。
http://www.w3schools.com/jsref/jsref_indexof.asp
var str = "My pizza is better than yours. Dang right it's better than yours"
if str.indexOf("pizza") > -1
// do something cool
else
// do something different
答案 2 :(得分:1)
以下是一个完整的例子:
<html>
<head>
<title>Example Form</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
function checkForm() {
var text = document.test_form.word.value;
if (text.indexOf("Pizza") > -1) {
alert("error");
return false;
}
return true;
}
</script>
</head>
<body>
<form action="blah.cgi" name="test_form" onSubmit="return checkForm()">
<input id="mytext" type="text" name="word" />
<input type="submit" value="Submit" />
</form>
<body>
</html>
基本上,这里发生的是当提交表单时,它会调用javascript函数checkForm,它会检查文本是否包含单词Pizza(目前仅大写),如果是,则返回false,阻止提交表格。
答案 3 :(得分:-1)
您应该执行以下操作
如果您知道前面的所有关键字,您可以将它们存储在javascript对象中并编写逻辑。
1)您应该将已搜索过的所有关键字存储在某个数据库中
2)使用jquery'ajax并向该数据库发出请求并检查它是否已存在。
http://api.jquery.com/jQuery.ajax/
3)Ajax成功回调,因为你可以决定你想做什么
$.ajax({
url: "test.aspx",
success: function(){
// this tells you if it exists or not , the alert the user
}
});