简体   繁体   中英

Dynamically create a class name in 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.

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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