如何在HTML文档中重新初始化脚本? [英] How to reinitialize a script in an HTML document?
问题描述
我有一个文档,该文档使用 jscolor.com 库,以便用户能够选择和存储颜色.我还使用JQuery函数在屏幕上添加行,以便用户可以创建和定义多种颜色.问题是,当添加新行时,未针对添加的元素重新初始化Javascript.
I have a document that uses the jscolor.com library, for the user to be able to select and store a color. I'm also using a JQuery function to add rows to the screen, so the user can create and define a number of colors. The problem is, when the new row is added, the Javascript isn't re-initialized for the added elements.
这是有问题的代码:
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("<div id='addr" + i + "'>" +
"<div class='col-xs-4'>" +
"<input type='text' name='config_color[" + i + "][css]' id='input-color[" + i + "][css]' class='form-control' />" +
"</div>" +
"<div class='col-xs-2'>" +
"<input type='text' name='config_color[" + i + "][value]' id='input-color[" + i + "][value]' class='form-control jscolor' />" +
"</div>" +
"<div class='col-xs-2'>" +
"<input type='text' name='config_color[" + i + "][default]' id='input-color[" + i + "][default]' class='form-control' />" +
"</div>" +
"<div class='col-xs-4'>" +
"<input type='text' name='config_color[" + i + "][notes]' id='input-color[" + i + "][notes]' class='form-control' />" +
"</div>" +
"</div>");
$('#tab_logic').append('<div id="addr'+(i+1)+'"></div>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
}).trigger('change');
</script>
我在 JSFiddle 上做了一个简化的例子,您可以看到在第一行中,如果单击颜色单元格,则会弹出一个调色板.
I've made an simplified example of what I'm talking about on JSFiddle - you can see in the first row, if you click in the color cell, it gives you a pop up color palette.
如果添加其他行,则弹出选择器不起作用.
If you add additional rows, the popup picker doesn't work.
但是,所有数据都正确存储在数据库中,所以我有一个实例,其中Javascript添加的某些元素可以正常工作而其他元素却不能正常工作?
However, all of the data stores in the database properly, so i have an instance where some elements added by Javascript work properly and others don't?
(也是完全公开的信息,我先问过 Reddit -因此,这是一个交叉岗位.
(Also full disclosure, I asked on Reddit first - this is therefore a cross-post.
推荐答案
jscolor在其示例中,具有一个名为实例化新拾色器"的示例,向您展示如何执行此操作.
In their examples, jscolor has one called "Instantiating new Color Pickers" which shows you how to do it.
You're adding the new row as a string, which I wouldn't recommend, because if you created each input separately using jQuery it would be easier to call jscolor()
on only one element, but this works too.
只需将以下内容添加到您的点击处理程序中即可:
Just add the following to your click handler:
// Get all the inputs first
var allInputs = $('.jscolor');
// From there, get the newest one
var newestInput = allInputs[allInputs.length - 1];
// And call jscolor() on it!
new jscolor(newestInput);
这是更新的小提琴
这篇关于如何在HTML文档中重新初始化脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!