doujie1917 2016-12-28 05:36
浏览 33
已采纳

如何使用PHP创建动态类并使用jQuery

I am going to create a PHP snippet or can be considered as WordPress code snippet, and want to create a dynamic css class each time that module loaded on the front end, and that class will be used by jQuery to style my front end.

Here is the scenario:

Let suppose first time module loaded on front end, it should have a class like: module-front-end-123 and I can use this exact class from jQuery to style its content according to data living inside this module only.

And now suppose another module of same type added now it should generate some class like module-front-end-124 and I will be using this class from jQuery again to out put its styling as well.

Advantage of this approach will be this, I'll be writing my code snippet only once and when ever module gets loaded I'll be getting its own class and jQuery code will work on this module and for other module style will be working for other module independently.

I can create that class by PHP but don't know how to use that class in jQuery or any thing like that ...

Can anyone guide me please? I just want to write my style only once and each time that will applied to fetched class.

  • 写回答

1条回答 默认 最新

  • doumian3780 2017-01-02 01:18
    关注

    Inside your PHP code you can use any variable which increments value after each code snippet gets inserted. Like shown below:

    On top of the php code add:

     global $count;
     if $count == '' { $count = 0; }
    

    It will just create a variable of global scope and if its empty it will set it to 0. Perfect, now just use this variable in your html class like shown below:

    <div class="module-front-end-<?php echo $count;?>">HTML DATA GOES HERE </div> <?php $count++; ?>
    

    Now in first insertion it will generate module-front-end-0 and in second insertion it will become module-front-end-1 and so on with each insertion of module.

    Now just add another class, like get-data and your code will become like shown below:

    <div class="get-data module-front-end-<?php echo $count;?>">HTML DATA GOES HERE </div>
    

    So, your html part done now move to JS part, Inside your JS file just add code like shown below:

    var count = 0;
    $(".get-data").each(function(){
        $('module-front-end-'+count+).append('<p>this is my data</p>');
        count = count + 1;
    }):
    

    This way it will do the work for you. Note: .append('<p>this is my data</p>'); is just for example purposes to show that how can you go inside your every dynamic class. You can do what ever you want to do with your code there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部