【问题标题】:How do I stop the page reload after selecting an autocomplete suggestion选择自动完成建议后如何停止页面重新加载
【发布时间】:2012-06-22 23:08:46
【问题描述】:

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

我希望这发生在 3 个场景中:

  1. 用户输入标签,忽略自动完成建议并按下回车键。
  2. 在输入查询的任何部分后,用户使用箭头键选择自动完成建议之一并按 Enter。
  3. 在输入查询的任何部分后,用户会用鼠标单击自动完成建议之一。

我已经能够让场景 1 完美运行。但是,场景 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();
}

场景一代码:

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 进行自动完成。

【问题讨论】:

  • 我想我诊断出了问题。我很确定这是输入标签提交。每当页面重新加载时,url 都会在末尾附加“?newTag=[value]”。我会更新我找到的任何解决方案。
  • 另外,当我执行场景 2 时,它会遍历场景 1,直到 addTag() 函数的第一行之前。

标签: javascript jquery ajax autocomplete pylons


【解决方案1】:

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

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

我在方案 1 中通过防止在用户按下回车时发生默认事件来解决此问题。但由于我无法在 jQuery 事件 .autocomplete() 中访问此事件,因此无法阻止它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2014-08-08
    • 2019-12-20
    • 2020-09-05
    相关资源
    最近更新 更多