如何使用.attr()或.on('点击',来自同一来源?)动态获取自动完成值?

时间:2015-06-24 21:40:09

标签: javascript php jquery json getjson

我有两个输入字段。

<input type="text" name="image" />
<input type="text" name="file" />

的Javascript

 $('input[name=\'image\'], input[name=\'file\']').autocomplete({ 
    minLength: 2,
    source: function( request, response ) {
        var thisType = $(this).attr('name');
        $.getJSON( "files/", {
            term: extractLast( request.term ),
            type: thisType
        }, response );
    },
    create: function () {
        var thisType = $(this).attr('name');
        if (thisType == 'image') {
            $(this).data("autocomplete")._renderItem = function(ul, item) {
                return $("<li></li>")
      .data("item.autocomplete", item)
     .append('<a><img src="files/' + item.label + '.jpg" />' + item.label + '</a>')
                    .appendTo( ul );
            };
        } else {
            $(this).data("autocomplete")._renderItem = function(ul, item) {
                return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append('<a>' + item.label + '</a>')
                    .appendTo( ul );
            };
        }
    },
    });

PHP

 <?php
    if (empty($_GET['term'])) exit;

    $q = strtolower($_GET["term"]);

    $type = strtolower($_GET["type"]);

    if (get_magic_quotes_gpc()) $q = stripslashes($q);

    $files = array();

    if ($type == 'image') {
        foreach(glob('image/*.jpg*', GLOB_BRACE) as $key=>$file) {
            $files[] = substr($file, 0, -4);
        }
    } else {
        foreach(glob('image/*.txt*', GLOB_BRACE) as $key=>$file) {
            $files[] = substr($file, 0, -4);
        }
    }

    $files = array_unique($files);
    $files = array_combine($files, $files);

    $result = array();
    foreach ($files as $key=>$value) {
        if (strpos(strtolower($key), $q) !== false) {
   array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
        }
        if (count($result) > 11) break;
    }

    echo json_encode($result);

我希望当我输入第一个输入时,结果需要向我显示带有预览的图像文件名称,当输入第二个输入时,结果需要向我显示文本文件名称。有什么方法可以如果单击或类型或使用attr动态获取来自同一来源的每个输入的值?我试图将此链接起来但不起作用..

0 个答案:

没有答案