草庐IT

javascript - 在 JQuery ui 自动完成中显示图像

coder 2024-04-28 原文

我有一个带有 JQuery ui 自动完成功能的脚本,效果很好。有一个显示用户名字和姓氏的搜索过程。但是在我的数据库中,还有用户的照片,我想在建议中显示它的名字和姓氏。

(在数据库中,pic包含图片url)

脚本:

$(function() {    
    $("#search").autocomplete({
        source: "autocomplete.php",
        minLength: 1,
        select: function(event, ui) {
            var url = ui.item.id;
            if(url != '') {
                location.href = '...' + url;
            }
        },   
        html: true,           
        open: function(event, ui) {
            $(".ui-autocomplete").css("z-index", 1000);   			
        }
    });    	
});

autocomplete.php

<?php     
if ( !isset($_REQUEST['term']) ) {
	exit;
}
 
$mysqli = new MySQLi($DB_host,$DB_login,$DB_pass,$DB_select);
     
$term = trim(strip_tags($_GET['term'])); 
$term = preg_replace('/\s+/', ' ', $term);
 
$a_json = array();
$a_json_row = array();
 
$a_json_invalid = array(array("id" => "#", "value" => $term, "label" => "Only letters and digits are permitted..."));
$json_invalid = json_encode($a_json_invalid);
 
if(preg_match("/[^\040\pL\pN_-]/u", $term)) {
  print $json_invalid;
  exit;
}

if ($data = $mysqli->query("SELECT * FROM users WHERE firstname LIKE '%$term%' OR lastname LIKE '%$term%' ORDER BY firstname , lastname")) {
	while($row = mysqli_fetch_array($data)) {
		$firstname = htmlentities(stripslashes($row['firstname']));
		$lastname = htmlentities(stripslashes($row['lastname']));
		$id= htmlentities(stripslashes($row['id']));
		$pic= htmlentities(stripslashes($row['pic']));
		$a_json_row["id"] = $id;
		$a_json_row["value"] = $firstname.' '.$lastname;
		$a_json_row["label"] = $firstname.' '.$lastname;
		array_push($a_json, $a_json_row);
	}
}
 
/* jQuery wants JSON data */
echo json_encode($a_json);
flush();
 ?>

请帮忙。

最佳答案

你只需要有一个 <img>元素准备接收 img URL...
然后在选择时,将 URL 传递给 src属性。

在下面的演示中,我模拟了您的 json 响应....
尝试使用“John Doe”或“System Admin”。

$(function() {
  $("#search").autocomplete({
    source: //"autocomplete.php",
    [
      {
       id:"John Doe",
       value:"John Doe",
       label:"John Doe",
       img:"http://images.maskworld.com/is/image/maskworld/bigview/john-doe-foam-latex-mask--mw-117345-1.jpg"
      },
      {
       id:"System Admin",
       value:"system Admin",
       label:"system Admin",
       img:"http://www.ericom.com/imgs/braftonArticles/3-things-every-system-admin-should-know-about-virtualization_16001411_800906167_0_14057272_500.jpg"
      }
    ],
    minLength: 1,
    select: function(event, ui) {
      /*
      var url = ui.item.id;
      if(url != '') {
        location.href = '...' + url;
      }
      */
      var img = ui.item.img;
      $("#pic").attr("src",img);
    },
    html: true, 
    open: function(event, ui) {
       $(".ui-autocomplete").css("z-index", 1000);
    }
  });
});
img{
  max-height:350px;
  max-width:200px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input type="text" id="search"><br>
<img id="pic">


编辑

也许您希望在下拉列表中显示图片...
我在 jQuery-UI documentation 中找到了这个.

$(function() {

      $("#search").autocomplete({
        source: //"autocomplete.php",
        [
          {id:"John Doe",
           value:"John Doe",
           label:"John Doe",
           img:"http://images.maskworld.com/is/image/maskworld/bigview/john-doe-foam-latex-mask--mw-117345-1.jpg"},
          {id:"system Admin",
           value:"system Admin",
           label:"system Admin",
           img:"http://www.ericom.com/imgs/braftonArticles/3-things-every-system-admin-should-know-about-virtualization_16001411_800906167_0_14057272_500.jpg"}
        ],
        minLength: 1,
        select: function(event, ui) {
          /*
          var url = ui.item.id;
          if(url != '') {
            location.href = '...' + url;
          }
          */
        },
        html: true, 
        open: function(event, ui) {
          $(".ui-autocomplete").css("z-index", 1000);

        }
      })
        .autocomplete( "instance" )._renderItem = function( ul, item ) {
        return $( "<li><div><img src='"+item.img+"'><span>"+item.value+"</span></div></li>" ).appendTo( ul );
      };

    });
.ui-menu img{
  width:40px;
  height:40px;
}
.ui-menu li span{
  font-size:2em;
  padding:0 0 10px 10px;
  margin:0 0 10px 0 !important;
  white-space:nowrap;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input type="text" id="search"><br>

关于javascript - 在 JQuery ui 自动完成中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45662200/

有关javascript - 在 JQuery ui 自动完成中显示图像的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  5. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  6. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  7. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  8. ruby-on-rails - 复数 for fields_for has_many 关联未显示在 View 中 - 2

    目前,Itembelongs_toCompany和has_manyItemVariants。我正在尝试使用嵌套的fields_for通过Item表单添加ItemVariant字段,但是使用:item_variants不显示该表单。只有当我使用单数时才会显示。我检查了我的关联,它们似乎是正确的,这可能与嵌套在公司下的项目有关,还是我遗漏了其他东西?提前致谢。注意:下面的代码片段中省略了不相关的代码。编辑:不知道这是否相关,但我正在使用CanCan进行身份验证。routes.rbresources:companiesdoresources:itemsenditem.rbclassItemi

  9. ruby-on-rails - 从应用程序中自定义文件夹内的命名空间自动加载 - 2

    我们目前正在为ROR3.2开发自定义cms引擎。在这个过程中,我们希望成为我们的rails应用程序中的一等公民的几个类类型起源,这意味着它们应该驻留在应用程序的app文件夹下,它是插件。目前我们有以下类型:数据源数据类型查看我在app文件夹下创建了多个目录来保存这些:应用/数据源应用/数据类型应用/View更多类型将随之而来,我有点担心应用程序文件夹被这么多目录污染。因此,我想将它们移动到一个子目录/模块中,该子目录/模块包含cms定义的所有类型。所有类都应位于MyCms命名空间内,目录布局应如下所示:应用程序/my_cms/data_source应用程序/my_cms/data_ty

  10. ruby-on-rails - 在 Flash 警报 Rails 3 中显示错误消息 - 2

    如果我在模型中设置验证消息validates:name,:presence=>{:message=>'Thenamecantbeblank.'}我如何让该消息显示在闪光警报中,这是我迄今为止尝试过的方法defcreate@message=Message.new(params[:message])if@message.valid?ContactMailer.send_mail(@message).deliverredirect_to(root_path,:notice=>"Thanksforyourmessage,Iwillbeintouchsoon")elseflash[:error]

随机推荐