doutuanxiao4619 2017-12-04 16: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-04 18: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();
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部