简体   繁体   English

如何根据选择框值复制 div 一定次数?

[英]How can I replicate a div a certain number of times based on a select-box value?

I am trying to make a script that, when I choose in the dropdown 4, the div is repeated 4 times.我正在尝试制作一个脚本,当我在下拉列表 4 中选择时,该 div 重复 4 次。

<div>repeat<div>

<script type = "text/javascript">
    document.write('<select>')
    for (var i = 0; i < 10; i++) {
        document.write('<option value=' + i + '>' + i + '</option>');
    }
    document.write('</select>')
</script>

Now the problem is repeat the number of times that the user choose in dropdown.现在的问题是重复用户在下拉列表中选择的次数。

demo演示

First, don't use document.write .首先, 不要使用document.write

You've tagged your question with jQuery and so I'm assuming that you're using that.您已经用 jQuery 标记了您的问题,所以我假设您正在使用它。

Something like this should work ( fiddle ):像这样的东西应该工作(小提琴):

HTML: HTML:

<div id="repeatDiv">repeat</div>

<select id = "mySelect">
   <option value = "1">1</option>
   <option value = "2">2</option>
   <option value = "3">3</option>
   ...
   <option value = "10">10</option>
</select>

Javascript: Javascript:

jQuery("#mySelect").change(function() {
   var value = jQuery(this).val();
   var $repeatDiv = jQuery("#repeatDiv");

   for(var i = 0; i < value; i++) {
       $repeatDiv.after($repeatDiv.clone().attr("id", "repeatDiv" + new Date().getTime()));
   }
});

I modified my solution to use a clone and give each element unique id's.我修改了我的解决方案以使用克隆并为每个元素提供唯一的 id。

The non-jQuery version is a little more verbose ( fiddle ):非 jQuery 版本更冗长(小提琴):

document.getElementById("mySelect").addEventListener("change", function(event) {
    var value = event.target.options[event.target.selectedIndex].value;
    var repeatDiv = document.getElementById("repeatDiv");

    for(var i = 0; i < value; i++) {
        var newDiv = document.createElement("div");
        newDiv.id = "repeat" + new Date().getTime();
        newDiv.innerHTML = repeatDiv.innerHTML;
        repeatDiv.parentNode.insertBefore(newDiv, repeatDiv.nextSibling); //essentially an insertAfter      
    }
}, true);

Listening to the "onchange" event on the select element will give you the feedback you need to modify the document structure.聆听 select 元素上的“onchange”事件将为您提供修改文档结构所需的反馈。 Fiddle example小提琴示例

HTML HTML

<div id="repeat"></div>

JavaScript JavaScript

var select_element = document.createElement("select");
var option_element;

for (var i = 0; i < 10; i++) {
    option_element = document.createElement("option");
    option_element.value = i;
    option_element.text  = i;
    select_element.appendChild(option_element);
}

select_element.addEventListener("change", function (event) {
    var repeat_container = document.getElementById("repeat");
    var div_element;

    // Remove previously added divs
    while (repeat_container.firstChild) {
      repeat_container.removeChild(repeat_container.firstChild);
    }

    // Add new divs
    for (var i = 0; i < event.currentTarget.value; i++) {
        div_element = document.createElement("div");
        div_element.style.backgroundColor = "rgb(0,255," + (i * 20) + ")";
        div_element.style.height = "10px";
        repeat_container.appendChild(div_element);
    }
}, false);

document.body.appendChild(select_element);

here is a neat demonstration:这是一个简洁的演示:

JSFiddle demo JSFiddle 演示

And here: the code used:在这里:使用的代码:

//NUMERATE SELECT
for (var i = 0; i < 10; i++) { // add counts in a for loop
    $('.select select').append('<option value=' + i + '>' + i + '</option>');
}
//#

//DUPLICATE PLUGIN
$.fn.duplicate = function(count, cloneEvents) {
    var tmp = [];
    for (var i = 0; i < count; i++) {
        $.merge(tmp, this.clone(cloneEvents).get());
    }
    return this.pushStack(tmp);
};

//SELECT CHANGE FUNCTION (on change get value and clone)
$('.select select').change(function(){  // on change...
    var numOfClones = $(this).val();    // get value...
    $('#holder').html('');              // empty holder if there are some old clones
    $('.repeat').duplicate(numOfClones).addClass('new').appendTo('#holder'); // duplicate; fill holder with new clones;
});

A simple solution if you can't use jQuery:如果您不能使用 jQuery,一个简单的解决方案:

HTML: HTML:

<select id="repeater" onChange="updateDivs(this);">
    <option value="1"> 1 </option>
    <option value="2"> 2 </option>
    <option value="3"> 3 </option>
    <option value="4"> 4 </option>
</select>

<div id="holder">

</div>

Javascript: Javascript:

function updateDivs(select){
     times=select.value;
    holder=document.getElementById("holder");
    while(holder.hasChildNodes()){
        holder.removeChild(holder.firstChild);
    }
    for(i=1; i<=times; i++){
        div = document.createElement("div");
        div.appendChild(document.createTextNode("Repeat" + i));
         holder.appendChild(div);
    }  
}

Document.write is a bad idea, you should try to modify dom tree using appendChild, removeChild etc. instead Document.write 是个坏主意,您应该尝试使用 appendChild、removeChild 等来修改 dom 树

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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