尝试将信息传递给基于 html 声明值的 laravel ajax jquery 函数



我是LaRavel/Ajax的初学者,并尝试在html类objectbutton中声明 object.name,如果单击,则 object.name 传递给另一个将在内容区域div中显示 object.name 的函数。

$(document).on('click', '.block-button', function(){
                // access current block instance by listening to touched class
                var block_id = $(this).attr('block-id');
    $.ajax({
                    // laravel route access
                    url: '{{ route("content:page") }}',
                    type: 'get',
                    data: {input_block: block_id},
                    beforeSend:function(){
                        //in jquery . for class and # for ID
                        //LOADING TEXT
                        $('#content-area').html('Loading........')
                    },
                    success: function(result){
                        $('#content-area').css('background-color', result.color);
                        var blockInfos = '<h3>'+result.name+'</h3><h3>'+result.content+'</h3>';
                        //Loop over objects if exist
                        var objectsInfos = '';
                        if (result.objects.length > 0) {
                            //Loop
                            $.each( result.objects, function( index, object ){
                                objectsInfos = objectsInfos + '<div><a href="" class="object-button" id="'+ +object.name+ '">'+object.name+'</a></div>';

                            });
                        }

                        $('#content-area').html(blockInfos + objectsInfos);
                    }

                });});

正如您在代码中看到的那样,im 尝试在 HTML 的 ID 中传递 object.name,有没有办法将 object.name 放在 HTML 链接中,以便我可以使用另一个 OnClick 函数检索它,这将如何工作? 我不确定是否可以用 HTML 以这种方式做到这一点。谢谢!

好的,

所以根据您的评论,这就是我理解您想要的: 因此,您希望根据从 ajax 调用接收回来的数据输出许多可点击的元素。然后从这些元素中,一旦单击,它将显示它们包含的任何信息。

因此,考虑到这一点,您需要执行以下操作:

目前,您遍历收到的对象并创建一些锚链接来表示数据。您需要添加一些内容才能在单击时收听,还需要添加一些内容来识别它,以便您知道要显示的内容。

$.each(result.objects, function(index, object){
    objectsInfos = objectsInfos + '<div><a class="object-button" id="'+ +object.name+ '" data-contents="x">'+object.name+'</a></div>';
});

所以在这里我们看到你已经添加了一个名为object-button的类,这很好,因为我们可以使用它来监听点击。您还在 id 属性中添加了名称,因此当单击它时,我们知道它是什么。我添加了 data-content="x",因为这是您评论中使用的示例。

所以现在我们要监听点击然后显示内容。

$('body').on('click', '.object-button', function(){
    // get the id and contents
    var target_id = $(this).attr('id');
    var contents = $(this).attr('data-contents');
    // All we do now is display the contents
    $('#content-area').html(contents);
});

最新更新