如何从特定事件目标获取数据

How to get data from specific event target

我正在尝试使用 list 中的点击事件提取街道名称 list 使用 AJAX 成功回调获取地址数据的整个过程运行良好 我添加了一个成功的回调包含他点击的街道信息的客户对话框。

但在成功对话中的街道表演时,我只想获取街道名称并将其传输到输入 hidden 我希望使用那条街道的名称,以便将来,当客户单击一个按钮时,复制 AJAX 表单的地址,可以使用这条街道的名称在我的 API 中进行搜索,以便在 return 中执行此操作return 该地址的扩展版本到我的表格。

但我想不出或找不到任何关于如何提取客户在列表中单击的街道名称的任何东西,他唯一可以 return 对我来说是在开始时生成的原始元素使用我的 API 中包含所有注册地址

的路由进行列表分组

我已经尝试通过生成的元素的 class 获取数据,但结果是 none.. 我想过尝试向被点击的地址添加一个 ID 但我在 jQuery 文档中找不到任何可以帮助我的东西。

我的elements.js

$(document).ready(function(){
    // Setup Modal
    $('#openSearchAddress').click(function() { 
        // Start Modal
        $('#modalSearchAddress')
           .modal('show')
        ;
    });

    $('#sendSearchAddress').click(function() {
        $.ajax({
            type: "GET",
            dataType: "JSON",
            url: "https://****-api.herokuapp.com/api/itapetininga-street-last-three-searcheds?access_token=7Z****",
            success: function (finalData) {
                // Running test
                console.log(finalData);

                if (finalData) {
                    // var dd = JSON.parse(result);
                    // addressStreet(finalData[0].addressStreet)
                    // name: finalData[0].addressStreet

                    // Print Results
                    var options = {
                        valueNames: ['addressStreet', 'neighborhoodStreet']
                    };

                    // Example One
                    var values = finalData.map(function(finalDatum) {
                        return {
                            addressStreet: finalDatum.addressStreet,
                            neighborhoodStreet: finalDatum.neighborhoodStreet,
                        };
                    });

                    var userList = new List('users', options, values);

                    // Start Selected Address With Event Delegation
                    $("#target_ul").on("click", "li", function(event) {
                        // Prevent Redirect In Click
                        event.preventDefault();

                        // Load Options For Notification
                        var placementFrom = "top";
                        var placementAlign = "center";
                        var colorName = "bg-light-green";

                        // Set Options For Notification
                        showNotification(colorName, null, placementFrom, placementAlign);

                        // Start New Notification
                        function showNotification(colorName, text, placementFrom, placementAlign, animateEnter, animateExit) {
                            if (colorName === null || colorName === '') { colorName = 'bg-black'; }
                            if (text === null || text === '') { text = 'Endereço que você selecionou é '; }
                            if (animateEnter === null || animateEnter === '') { animateEnter = 'animated fadeInDown'; }
                            if (animateExit === null || animateExit === '') { animateExit = 'animated fadeOutUp'; }
                            var allowDismiss = true;
                            // Start Modern Structure For Notification
                            $.notify({
                                message: text
                            }, {
                                type: colorName,
                                allow_dismiss: allowDismiss,
                                newest_on_top: true,
                                timer: 1000,
                                placement: {
                                    from: placementFrom,
                                    align: placementAlign
                                },
                                animate: {
                                    enter: animateEnter,
                                    exit: animateExit
                                },
                                template: '<div data-notify="container" class="bootstrap-notify-container alert alert-dismissible {0} ' + (allowDismiss ? "p-r-35" : "") + '" role="alert">' +
                                    '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
                                    '<span data-notify="icon"></span> ' +
                                    '<span data-notify="title">{1}</span> ' +
                                    '<span data-notify="message">{2}</span>' +
                                    '<div class="progress" data-notify="progressbar">' +
                                    '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
                                    '</div>' +
                                    '<div id="selectedAddress"></div>' +
                                    '<a href="javascript:void(0);" class="alert-link" id="selectedSearchAddress" hidden></a>' +
                                    '<a href="{3}" target="{4}" data-notify="url"></a>' +
                                    '</div>'
                                }
                            );
                        }

                        // Add Selected Address In Notification
                        var selectedAddress = $( this ).text();

                        console.log('Selected address is: ', selectedAddress);

                        if (event.target && event.target.nodeName === 'LI') {
                            let item = event.target;

                            $("#selectedAddress").html(item.innerHTML);
                        }

                        // Prepare Input Hidden For Import Data To Form

                        // Add Informations About Selected Address
                        $('#selectedSearchAddress').text(selectedAddress);
                    });

                    // Print Variable Contain Native Data From All Street In List
                    console.log(values);
                }
            }
        }); 
    });

我在 EJS 模板中的列表

<div id="modalSearchAddress" class="ui small modal" style="margin-bottom: 53px !important;margin-top: 60px !important;margin-left: auto !important;margin-right: auto !important;">
    <div class="content" style="padding: 0rem !important;">
        <div class="row" style="margin-left: -30px !important; margin-right: -30px !important;">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <div id="users">
                    <div class="col-xs-12">
                        <div class="card" style="margin-bottom: 0px !important;">
                            <div class="header bg-indigo">
                                <h2 class="align-center">
                                    Pesquisar Endereço
                                    <small>Aqui você pode encontrar qualquer endereço cadastrado em seu catálogo...</small>
                                </h2>
                            </div>
                        </div>
                    </div>

                    <div class="col-xs-12">
                        <div style="background: #eeeeee; padding-top: 10px; padding-left: 10px; padding-right: 10px; padding-bottom: 3px;">
                            <div class="input-group" style="margin-bottom: 0px !important;">
                                <div class="form-line">
                                    <input type="text" class="form-control search align-center" id="nameSearchAddress" placeholder="Pesquise por endereços cadastrado em seu catálogo...">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-xs-12" >
                        <ul class="list list-search-address" id="target_ul">
                            <li>
                                <h3 class="addressStreet">Test</h3>
                                <p class="neighborhoodStreet">Test</p>
                            </li>
                        </ul>
                    </div>

                    <div class="col-xs-12">
                        <div class="btn-group btn-group-justified" role="group" aria-label="Justified button group">
                            <a href="javascript:void(0);" class="btn bg-indigo waves-effect sort" role="button" data-sort="name">CLASSIFICAR POR NOME</a>
                            <a href="javascript:void(0);" class="btn bg-indigo waves-effect" role="button" id="sendSearchAddress">ATUALIZAR</a>
                            <a href="javascript:void(0);" class="btn bg-indigo waves-effect" role="button">COPIAR PARA FORMULARIO</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

非常感谢你帮助我,我已经尝试了两天... 成功数据 (finalData) return编辑者 Ajax

[{
    "addressStreet": "Rua Baltazar Lorenzetto",
    "neighborhoodStreet": "Jardim Brasil",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "18214-490",
    "cityStreet": "Itapetininga",
    "stateStreet": "São Paulo",
    "id": "5a90b6b5c59ccc00148766b1"
}, {
    "addressStreet": "Rua Doutor Campos Sales",
    "neighborhoodStreet": "Centro",
    "latStreet": "-23.588984",
    "lngStreet": "-48.050931",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Itapetininda",
    "stateStreet": "São Paulo",
    "id": "5a94332d03d2a4001407a07c"
}, {
    "addressStreet": "Rua José de Almeida Carvalho",
    "neighborhoodStreet": "Centro",
    "latStreet": "-23.5785848",
    "lngStreet": "-48.027667",
    "postalCodeStreet": "18200-354",
    "cityStreet": "Itapetininga",
    "stateStreet": "São Paulo",
    "id": "5a948a0f03d2a4001407a07d"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb0e4a086fb0014b65b45",
    "term": "Rua Ba"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb0e5a086fb0014b65b46",
    "term": "Rua Bal"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb0e7a086fb0014b65b47",
    "term": "Rua Balta"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb135a086fb0014b65b4b"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb136a086fb0014b65b4c"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb136a086fb0014b65b4d"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb15aa086fb0014b65b50"
}]

单击列表后我的控制台中的响应

elements.js:85 (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
elements.js:189 (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
elements.js:174 Selected address is:  
            Rua Baltazar Lorenzetto
             Jardim Brasil

试试这个

              $("#target_ul").on("click", "li", function(event) {
                    var self = $(this);         // Storing the reference of the element
                    ...................... // Your code as is
                    ......................
                    // Add Selected Address In Notification
                    var selectedAddress = $( self ).text();       // Using the reference of the stored element
                    ....................... // Your code as is
                    .......................

对于和我有同样疑问的人,请分析我们的朋友@AkshayKhandelwal 告诉我的更多内容。我试图请求与 Api Get 开始时不再相同的信息。通过获取特定目标,我们无法访问在函数开头返回的原始 JSON 访问权限。通过解决方案,我决定选择使用 ANGULAR JS 构建一个控制器,利用这种方法获取我们的事件变得更加可操作和可扩展。

// Query Address In Catalog
$('#openSearchAddress').click(function() { 
    // Start Modal
    $('#modalSearchAddress')
       .modal('show')
    ;
});

The call of modal remains the same

angular.module('YourModuleName', [You can extend it using other libraries])
.controller('MyCtrl', function ($scope, $http) {
    $http({
        method: "GET",
        url: "Your API Link"
    }).then(function mySuccess(response) {
        // Print JSON in console
        // $scope.myWelcome = response.data;

        $scope.iconType = 'fa fa-circle-o';

        $scope.data = {
            showDelete: false
        };

        $scope.edit = function (item) {
            alert('Edit Item: ' + item.addressStreet);
        };

        $scope.clicker = function (item) {
            alert('Clicked chevron: ' + item.addressStreet)
        };
        $scope.share = function (item) {
            alert('Share Item: ' + item.addressStreet);
        };

        $scope.moveItem = function (item, fromIndex, toIndex) {
            $scope.items.splice(fromIndex, 1);
            $scope.items.splice(toIndex, 0, item);
        };

        $scope.onItemDelete = function (item) {
            $scope.items.splice($scope.items.indexOf(item), 1);
        };

        $scope.circleClicked = function (item) {
            alert('You selected Item: ' + item.addressStreet);
        }

        // Set Scope Contains Response Data
        $scope.items = response.data;
    }, function myError(response) {
        $scope.myWelcome = response.statusText;
    });
});

我不得不在前端恢复我们的结构,你可以在这里添加分页、查询、过滤器、突出显示,任何你想要的。您可以根据自己的喜好自定义样式 sheet:]

            <div class="col-xs-12">
                <ul class="list-search-address">
                    <li ng-repeat="item in items | filter : search" item="item" href="#/item/{{item.id}}" style="display: block; background-color: #eee; padding: 10px; box-shadow: inset 0 1px 0 #fff;">
                        <h3 style="font-size: 16px; margin: 0 0 0.3rem; font-weight: normal; font-weight: bold;">
                            <i ng-class="iconType" ng-mousedown="iconType='fa fa-check-circle-o'" ng-mouseup="iconType='fa fa-circle-o'" ng-click="circleClicked(item)"></i>{{ item.addressStreet }}</h3>
                        <p>{{ item.neighborhoodStreet }}</p>
                    </li>
                </ul>
            </div>

谢谢启发我的思路xD