doujie1917 2016-12-28 13: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 09: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.

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效