javascript - 选择自动完成建议后如何停止页面重新加载

标签 javascript jquery ajax autocomplete pylons

我为表单输入字段创建了自动完成功能,允许用户将标签添加到标签列表中。如果用户选择任何建议,我希望页面将新标签添加到已存在的标签部分,而无需重新加载页面。

我希望这在 3 种情况下发生:

  1. 用户输入标签,忽略自动完成建议并按 Enter 键。
  2. 输入查询的任意部分后,用户可以使用箭头键选择一项自动完成建议,然后按 Enter 键。
  3. 输入查询的任意部分后,用户可以使用鼠标点击自动完成建议之一。

我已经能够完美地实现场景 1。然而,场景 1 和 2 使页面重新加载,但仍然没有将标签添加到列表中。

场景1和2都是由同一个函数调用的:

$j("#addTag").autocomplete({
  serviceUrl:'/ac',
  onSelect: function(val, data){
    addTag(data);
  }
});

这是 addTag() 的代码:

function addTag(tag){
  var url = '/addTag/' + tag;

  //Call the server to add the tag/
  $j.ajax({
    async: true,
    type: 'GET',
    url: url,
    success:function(data){
      //Add the tag to the displayed list of already added tags
      reloadTagBox(data);
    }, 
    dataType: "json"
  });

  //Hide the messages that have been displayed to the user
  hideMessageBox();
}

场景1代码:

function addTagByLookup(e, tag){
  if(e && e.keyCode == 13)
  {
    /*This stops the page from reloading (when the page thinks 
      the form is submitted I assume).
    */
    e.preventDefault();
    //If a message is currently being displayed to the user, hide it
    if ($j("#messageBox").is(":visible") && $j("#okayButton").is(":visible")){
      hideMessageBox();
    }

    else{  
      //Give a message to the user that their tag is being loaded
      showMessageBox("Adding the tag <strong>"+tag+"</strong> to your station...",'load');

      //Check if the tag is valid
      setTimeout(function(){
        var url = '/checkTag/' + tag;
        var isTagValid = checkTag(tag);

        //If the tag is not vaid, tell the user.
        if (isTagValid == false){
          var message = "<strong>"+tag+"</strong>"+
                      " was not recognized as a valid tag or artist. Try something   else.";
          //Prompt the user for a different tag
          showMessageBox(message, 'okay');
        }

        //If the tag is valid
        else{
          addTag(tag);
        }
      }, 1000);
    }
  }
}

我知道我在场景 1 中使用了 e.preventDefault 功能进行普通表单提交,但我似乎无法使其与其他场景一起使用,而且我什至不确定这是真正的问题。

我使用 pylons 作为 MVC 并使用 this tutorial用于自动完成。

最佳答案

所以,如果有人想知道,我的问题有一个简单的解决方案,而我一开始就不应该有。

我的输入标签嵌入在每次激活输入标签时提交的表单中。

我在场景 1 中通过阻止用户按 Enter 键时发生默认事件来解决此问题。但由于我无法在 jQuery 事件 .autocomplete() 中访问此事件,因此我无法阻止它。

关于javascript - 选择自动完成建议后如何停止页面重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11145033/

相关文章:

javascript - 如何配置我的 Derby.js 应用程序以使用 LESS CSS 引擎?

javascript - qTip2 中的 Ajax 表单

javascript - 我是否为 JSON 字符串数组正确构建了 JavaScript 对象?

javascript - 我的 jQuery 函数加载速度是否太慢?

php - 在页面中加载页面

javascript - 通过软件包安装程序安装时,Knockout 未定义

javascript - Grunt、Gulp.js 和 Bower 之间有什么区别?为什么以及何时使用它们?

javascript - 通过 jQuery AJAX 将数据发布到 Python CGI 脚本

javascript - addeventlistener 不会在 onclick/submit 上触发

javascript - 我怎样才能在页面加载时首先调用 setTimeout 然后等待五秒钟?