如何将颜色选择器函数集成到动态文本字段中

How to Integrate Color Picker Function into Dynamic Text Field

本文关键字:动态 文本 字段 集成 函数 颜色 选择器      更新时间:2023-09-26

我目前在创建集成了颜色选择器功能的动态文本字段时遇到了一些问题。

以下是HTML代码:

<div id="color_div">
    <input type="text" name="color" id="p_color" maxlength="7" value="#365EBF">
    <a href="#" id="addColor">Add Color Picker</a>
</div>

创建动态文本字段的javascript功能运行良好:

/* -----------------------------------------------
                    Add Multiple Color
----------------------------------------------- */
        var multiple_color = 1;
        $('#addColor').click(function() {
                multiple_color++;
                event.preventDefault ? event.preventDefault() : event.returnValue = false;  
                $('#color_div').after('<div id="color_div2"><input type="text" name="color[]" id="p_color" maxlength="7" value="#365EBF"><a href="#" id="remColor">Remove</a></div>');
                return false;
        });
        $(document).on('click', '#remColor', function() {
            event.preventDefault ? event.preventDefault() : event.returnValue = false;
            $('#remColor').parents('#color_div2').remove(); 
            return false;   
        });

这是调用颜色选择器函数的代码,但它只适用于开头存在的文本字段。对于动态创建的文本字段,它不起作用。

$(document).ready(function() {
    $('#p_color').colorpicker()
})

我该怎么解决这个问题?

第一个id应该是唯一的,因此您需要更改第二个颜色选择器的id。

第二,一旦你添加了动态项目,你就需要实例化它的颜色选择器

我会这样做:

var multiple_color = 1;
$('#addColor').click(function(e) { // include the e in the function so you can use e.preventDefault()
  e.preventDefault();  
  multiple_color++; // use this to keep ids unique
  
  var id = 'p_color' + multiple_color; // id of input
  
  $('.color_div')
      .last()
      .after('<div id="color_div' + multiple_color + '" class="colour_div"><input type="text" name="color[]" id="' + id + '" maxlength="7" value="#365EBF"><a href="#" class="remColor">Remove</a></div>');   // change link id remColor to class and add color_div class to div
      // add new div after the last div  - if you want to add it after the first colour picker then just put it back to use the id of the first colour picker div
  $('#' + id).colorpicker(); // instantiate color picker on the new object you just added
});
$(document).on('click', '.remColor', function(e) {  // change selector to class
  e.preventDefault();
  $(this).parent('.colour_div').remove(); // remove current div
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="color_div1" class="color_div"> <!-- add color_div class -->
    <input type="text" name="color" id="p_color1" maxlength="7" value="#365EBF">
    <a href="#" id="addColor">Add Color Picker</a>
</div>