Jquery 追加错误信息一次

Jquery append error message once

我有一个搜索字段,当它留空并单击 "search" 按钮时,会出现错误消息 "Please enter a search term"。这就是我想要发生的事情,但是当您再次单击它时,消息会一遍又一遍地附加。我希望它只附加一次。

这是 jquery 的样子:

$('#search').find('input[type=submit]').click(function(){
    if( ! $('input[name=keywords]').val()){
        $('#search input[name=keywords]').addClass('error');
        $( "#search" ).append( "<p class='errorMsg top'>Please enter a search term</p>" );
        //alert('Please enter a search term');
        return false;
    } else {
        _gaq.push(['_trackEvent', 'onsite_search', $('input[name=keywords]').val()]); 
    }

});

我试过在 if 语句前添加:

for i=0; i<1; i++

这完全关闭了该功能。我也尝试添加

.one('click', function{
})

这种方法很有效 -- 它允许您在搜索框为空时单击一次,给出错误消息,但在第二次单击时,将搜索处理为“”。

如有任何帮助,我们将不胜感激!

此外,我认为这并不重要,但这是 HTML:

<fieldset class="fieldset">
<legend>{lang:search_by_keyword}</legend>

<input type="text" class="input" maxlength="100" size="40" name="keywords" style="width:100%;" />

<div class="default">
<select name="search_in">
<option value="titles" selected="selected">{lang:search_in_titles}</option>
<option value="entries">{lang:search_in_entries}</option>
<option value="everywhere" >{lang:search_everywhere}</option>
</select>

</div>

有一个变量来检查用户是否已经收到警告怎么样?然后,如果他没有收到警告,您只需附加错误消息即可。

var alerted = false;

$('#search').find('input[type=submit]').click(function(){

    if( ! $('input[name=keywords]').val() && ! alerted){

        alerted = true;
        $('#search input[name=keywords]').addClass('error');
        $( "#search" ).append( "<p class='errorMsg top'>Please enter a search term</p>" );
        //alert('Please enter a search term');
        return false;
    } else {
        alerted = false; //alternatively, check if a <p> tag with class errorMsg exists and then set alerted = false
        _gaq.push(['_trackEvent', 'onsite_search', $('input[name=keywords]').val()]); 
    }

});

在 post 错误消息

时使用 .html 而不是 .append