简体   繁体   English

如何使用ajax调用将类添加或绑定到动态加载的数据的父元素和子元素?

[英]How to add or bind classes to both parent and child elements of dynamically loaded data using ajax call?

I am new to jQuery and am struggling here from past 1 week.I am loading the data from JSON array using an ajax call, And using a one "swipe" plugin to swipe and load all the images over my page on same div. 我是jQuery新手,从过去1周开始在这里苦苦挣扎。我使用ajax调用从JSON数组加载数据,并使用一个“ swipe”插件在同一div上滑动并加载页面上的所有图像。 But I don't know how to add the class to both parent div and child elements. 但是我不知道如何将类添加到父div和子元素。 my code is: 我的代码是:

    url : "http://my_ip/App/event_h/get_a_evnts",
    type:"POST",
    dataType:"json",
    success: function(data)
    {
        var event1=data.event1;
        var total_event=event1.length;
        var event1=data.event1;
        var DOM=$('#DOM');
        var path="http://my_ip/App/";
        var media1=data.media;
        var location=json.location; 
        var event2=data.event;
        var rating=data.rating;
        var event1[i].event_id =1;//this value also retrived from json array
        var output= '<div class="container-fluid" ><section class="row">';
            output +='<div class="col-sm-12 col-md-12 col-xs-12"><div class="panel panelstyle">';
            output +='<header><h1><small>Event : </small>'+event1[i].event_title+'</h1></header><div class="panel-body">';
            output +='<div id="div1" class="swiper-container" ><div  id="div2" class="swiper-wrapper"  >';
              for(j=0; j<media1.length; j++) {
                if(event1[i].event_id === media1[j].event_id){
                 output +='<img id="newimg" class="swiper-slide" src='+path+media1[j].media_path+' alt="new image" />';
                }
              }});

i didn't write complete code here only required part i have written an also in the above code everything is works fine not even a single error in console but .swiper-container,.swiper-container,.swiper-slide are not loading when the page loads so I cannot swipe my images. 我没有在此处编写完整的代码,仅在需要的部分编写了代码,在上面的代码中也一切正常,即使控制台中没有单个错误,但.swiper-container,.swiper-container,.swiper-slide均未加载时页面加载完毕,所以我无法滑动图像。 I have tried "on","delegate" an "bind" but am unable to attach those class when the page loads. 我已经尝试过“上”,“委托”一个“绑定”,但是在页面加载时无法附加这些类。

try this code: 试试这个代码:

output = $(output);
output.addClass(".swiper-container");

The parent element that you are referring to is not necessarily the immediate parent it can be any element present at when document is ready and the element on which you have to bind event is descendent of it. 您要引用的父元素不一定是直接父元素,它可以是文档准备好并且必须绑定事件的元素作为它的后代时出现的任何元素。 In worst case there is body element. 最坏的情况是有身体元素。

or 要么

You can add the slide event in inside the success function once the dynamically created html has been inserted into the page. 将动态创建的html插入页面后,就可以在成功函数中添加slide事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM