2

这是我正在尝试做的事情。我想将 jquery 自动完成添加到所有输入框中。最初我只有 2 个盒子,用户可以动态添加多个盒子。自动完成在前两个框中有效,但在动态添加的按钮中失败。

她的代码小提琴:http: //jsfiddle.net/HG2hP/

代码:

HTML:

<!doctype html>
<html>

    <head>
        <title>TakeMeHome</title>
        <!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> -->
        <!--<script type="text/javascript" src="js/jquery-1.9.0.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.10.0.custom.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.10.0.custom.min.js"></script>-->
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
         <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
         <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>
         <script type="text/javascript" src="js/app.js"></script>
         <link type="text/css" rel="stylesheet" href="css/design.css"/> 



    </head>

    <body>
        <center>
                Your Place:<input class="address" id="source" type="text"/><br/>
                <div id= "div1">Friend1:<input class="address" id="friend1" type="text"/></div><br/>
                <pre>
                <div id="button">Add!</div> <div id="button2">Remove</div></br>
            </pre>
            <div id="sumbit_button">GO!</div>
            <div id="map" style = "width: 500px; height: 500px"></div>

        </center>

    </body>

</html>

JS

$(document).ready(function() {

var geocoder;
var map;
var marker;
var friends_cnt = 1;
var friends = [];
var distance = [];

$('#button').click(function() {
    if (friends_cnt < 11) {
        $('<div  id = div' + (friends_cnt + 1) + '>Friend' + (friends_cnt + 1) + ':<input type="text" class="address"  id="friend' + (friends_cnt + 1) + '"/></div>').insertAfter('#div' + friends_cnt);
        friends_cnt++;
    } else {
        console.log("Limit reached");
    }
});

$('#button2').click(function() {
    if (friends_cnt > 1) {
        $('#friend' + friends_cnt).remove();
        $('#div' + friends_cnt).remove();
        friends_cnt--;
    }
});

geocoder = new google.maps.Geocoder();

$(function() {
    $(".address").autocomplete({
        source : function(request, response) {
            geocoder.geocode({
                'address' : request.term
            }, function(results, status) {
                response($.map(results, function(item) {
                    return {
                        label : item.formatted_address,
                        value : item.formatted_address,
                        latitude : item.geometry.location.lat(),
                        longitude : item.geometry.location.lng()
                    }
                }));
            })
        },
    });
});

$('#sumbit_button').on("click", function() {
    console.log("button clicked");
    var a = [];
    a.push($("#source").val());
    for ( i = 1; i <= friends_cnt; i++) {
        a.push($("#friend" + i).val());
    }

    console.log("a :");
    console.log(a);

    var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json";

    console.log("gurl :" + gurl);
    $.ajax({
        url : gurl,
        data : {
            origins : a.join('|').replace(/ /g, '+'),
            destinations : a.join('|').replace(/ /g, '+'),
            sensor : false
        },
        success : function(response) {
            console.log("response type :");
            console.log( typeof response);
            if ( typeof response == "string") {
                response = JSON.parse(response);
            }
            var rows = response.rows;
            for (var i = 0; i < rows.length; i++) {
                distance[i] = [];
                for (var j = 0; j < rows[i].elements.length; j++) {
                    distance[i][j] = rows[i].elements[j].distance.value;
                }
            }
        }
    });
    console.log("No.of friends is " + friends_cnt);
    console.log(distance);
});

});

CSS

input {
margin: 10px 4px;
}

#button, #button2 {

    width: 70%;
    margin: 0 auto;
}

.ui-autocomplete {
    background-color: white;
    width: 300px;
    border: 1px solid #cfcfcf;
    list-style-type: none;
    padding-left: 0px;
}

.ui-helper-hidden-accessible {
    display: none;
}

当我使用类概念来添加自动完成时,我应该得到结果。

你能告诉我我错在哪里吗?

4

4 回答 4

1

在您的点击事件中:

$('#button').click(function ()...

您应该在新添加的输入字段上设置自动完成,例如:

    $('#button').click(function () {
        if (friends_cnt < 11) {

        $('<div  id = div'+(friends_cnt+1)+'>Friend' + (friends_cnt+1) + ':<input type="text" class="address"  id="friend' + (friends_cnt+1) + '"/></div>').insertAfter('#div'+friends_cnt);

       $('div#div'+(friends_cnt+1)).autocomplete(...);

       friends_cnt++;

    }

    else {
        console.log("Limit reached");
    }

});

由于您的自动完成仅附加到当前 DOM,而不是动态添加的。

于 2013-03-06T13:24:02.953 回答
1

you must either re apply the auto complete to each element like Kapo suggested

 $('div#div'+(friends_cnt+1)).autocomplete(...);

or use liveuery (see this thread for more details on that)

于 2013-03-06T13:33:28.687 回答
0

当我得到答案时,代码中的这种更改对我有用:在$('#button').click(function () {函数中添加这个

$(function() {
   $("#friend"+(friends_cnt+1)).autocomplete({
      source: function(request, response) {  . .. . . 

这将在创建时为所有框添加自动完成功能。

于 2013-03-06T13:42:52.903 回答
0

On pageload your autocomplete attaches to fields with class .address, however on page load you do not have any .address field, so nothing gets attached.

You need to run

$(".address").autocomplete({

Right after you add your new field to the dom, or better still, make the input an object, and you can attach events straight to it like:

$input = $('input')
            .attr('type', 'text')
            .attr('class', 'address')
            .attr('id', 'friend')
            .autocomplete({ etc
于 2013-03-06T13:33:04.297 回答