doutuanxiao4619 2017-12-05 00:36
浏览 227
已采纳

在Javascript中动态创建类名

I have some code in PHP file that creates a button and the target of that button is a DIV (findOptionsBox).

The button gets repeated multiple times on the page and so the target of each button should be a unique DIV Id.

<button type="button" id="myBtn" class="btn" data-toggle="collapse" data-
 target="#findOptionsBox">
       ......
</button>

<div id="findOptionsBox" class="search-box collapse">
......
<div>

So my question is how to make 'findOptionsBox' a variable that can be supplied to the data-target of each myBtn and the same variable can also be the ID of the corresponding div.

I am looking to end up with something like this:

......

<div id="findOptionsBox_1" class="search-box collapse">
......
<div>

......

<div id="findOptionsBox_2" class="search-box collapse">
......
<div>

I need the btnIds and the DivIds to be unique and each btnId to refer to the corresponding DivId.

I am looking to do this in Javascript and am trying something like:

<script type="application/javascript">
    $(function(){
        var count = 0;

            count++;
    });
</script>

Thanks.

  • 写回答

1条回答 默认 最新

  • doujiao8491 2017-12-05 02:54
    关注

    https://jsfiddle.net/sudarpochong/0hx4mLaw/1/

    • Create a div to contain options box (#options-container)
    • Clone #findOptionsBox and change the id
    • Insert into #options-container

    Code:

    var PREFIX_ID = "findOptionsBox_";
    
    $("#myBtn").click(function(e) {
    
      $("#options-container").empty();
        var totalOptions = $("#numberOfOptions").val();
        for (var i=0; i<totalOptions; i++) {
        var newBox = $("#findOptionsBox").clone();
        newBox.attr("id", PREFIX_ID + i);
        newBox.appendTo("#options-container");
        newBox.show();
      }
    
      e.preventDefault();
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?