【问题标题】:Jquery UI autocomplete link to itemJquery UI 自动完成链接到项目
【发布时间】:2012-06-17 17:09:52
【问题描述】:

我想做一个搜索框,你可以在其中搜索数据库中的记录。

search.php 看起来像这样:

<?php
// connect to mysql
require_once('includes/connect.php');
// include config
include('includes/config.php');

$nameser = $_GET['term'];

$names = array();
$result = mysql_query("SELECT name,customerid FROM customers WHERE name LIKE '%".$nameser."%' ORDER BY name ASC");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $row_array['id'] = $row['customerid'];
    $row_array['value'] = htmlentities($row['name']);

    array_push($names,$row_array);
   }

echo json_encode($names);

?>

Javascript 部分如下所示:

    $("#tags").autocomplete({
        source: "search.php",
        minLength: 2,
        select: function(event, ui) {
          window.location = ("customers.php?action=view&cid=" + item.id)
          //$('#tags').val(ui.item.id);
          //return false;
        }
    })
    .data("autocomplete")._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
        .appendTo( ul );
    };

但是,这会产生错误:

ReferenceError: item is not defined

我想要发生的是,当我单击结果列表中的某些内容时,我会被重定向到 url

customers.php?action=view&cid={CustomerID}

有人有想法吗?

编辑:

正确有效的 Javascript 代码:

$("#tags").autocomplete({
    source: "search.php",
    minLength: 2,
    select: function(event, ui) {
      window.location = ("customers.php?action=view&cid=" + ui.item.id)
      //$('#tags').val(ui.item.id);
      //return false;
    }
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
    .data( "item.autocomplete", item )
    .append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
    .appendTo( ul );
};

【问题讨论】:

  • 第5行,js:什么是item?全局变量?
  • @Alex:我其实不知道——但它在第 13 行有效。脚本是从这里的其他帖子中复制/粘贴的。
  • 第 13 行 item 是传递给函数 _renderItem 的参数,所以没关系。请在select 事件之前发布链接的样子。
  • 并且还尝试查看ui对象,也许它包含选定的项目
  • @Alex:链接在列表中看起来正确。我不明白应该如何查看 ui 对象?

标签: php javascript jquery jquery-ui jquery-ui-autocomplete


【解决方案1】:

我在jsfiddle. you can see it here: 有一个带有工作示例的演示

关键是在autoselect select方法中获取一个有效的url值。请务必 console.log 记录 ui 值,以便您可以看到可供您使用的内容。我能够使用标准的 ui.item.value 值将用户发送到另一个页面。

测试我的演示:

1.) 进入输入框,输入“a”。 2.) 选择“http://www.utexas.edu” 3.) 新页面将加载。

【讨论】:

  • 谢谢!我需要做的就是将ui 添加到item.id 并且它可以工作!
猜你喜欢
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 2011-09-27
  • 2016-10-07
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多