我正在创建一个评论板,通过Javascript,我正在尝试实现一段脚本,如果其中包含不需要的单词,它将阻止用户提交段落。我在网上看过,很难找到任何例子。这是我到目前为止所拥有的,但不确定我是否应该使用 index.of
索引.php
<div class="askComment">
<h2>Submit new comment</h2>
<!--comment form -->
<form id="form" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo $post; ?>">
<input type="hidden" name="type" value="A">
<p>Hello <strong><?php echo $fname; ?></strong> what do you have to say</p>
<input type="hidden" name="fname" id="comment-name" value="<?php echo $fname; ?>" >
<input type="hidden" name="userid" id="comment-mail" value="<?php echo $UserId; ?>" >
<p>Your comment *</p>
<textarea name="comment" id="comment" cols="30" rows="10" placeholder="Type your comment here...." ></textarea>
<div id="error"></div>
<input type="submit" id="submit-comment" name="submit" value="Submit Comment">
</form>
</div>
mod_comment.php
$(document).ready(function () {
document.getElementById("submit-comment").disabled = true;
var swear = new Array();
swear[0] = "jelly";
swear[1] = "trumpet";
swear[2] = "chocolate";
$("#comment").change(function () {
var comment = $("#comment").val();
if (comment.indexOf('????') === -1) {
$("#error").html('<font color="red">Please rewrite <strong>bad</strong> word found.</font>');
} else {
document.getElementById("loginsubmit").disabled = false;
}
});
});
一种可能的解决方案(类似于您的,相同的逻辑,只是很少的更改/添加)。
http://jsfiddle.net/pK7DK/
$("#submit-comment").attr('disabled', true);
var swear = new Array();
swear[0] = "jelly";
swear[1] = "trumpet";
swear[2] = "chocolate";
$("#comment").on("keyup", function () {
var comment = $("#comment").val();
word = comment.split(' ');
for (i = 0; i < word.length; i++) {
worda = word[i].trim();
worda = worda.replace(/.|,|!|:| |;|?|r?n/g, ''); // bad word + one of chars = bad word
console.log(worda);
if ($.inArray(worda, swear) != -1) {
$("#error").html('<font color="red">Please rewrite <strong>bad</strong> word found.</font>');
$("#submit-comment").attr('disabled', true);
break;
} else {
$("#error").html('');
$("#submit-comment").attr('disabled', false);
}
}
});
我宁愿使用"keyup"事件,因此用户在键入时会收到错误消息。但是 - 如前所述,这很容易被覆盖,服务器端检查是必须的。
看看这个:http://www.w3schools.com/jsref/jsref_search.asp(搜索数组内的数组);
它可能不是最佳选择,但它将是代码的开始。
编辑:一个更好的选择(也许不是最好的)可能是将注释字符串按单词分隔成一个数组并在两个数组之间进行交集,这是一个解释如何在 js 中数组之间做交集的问题 JavaScript 中数组交集的最简单代码