我有一个循环,当它被调用时,会创建一个div,其中包含一些表单元素。每个div都基于一个变量“i”,为字段和div提供唯一的名称。有没有办法可以存储变量在创建div时的含义?
例如,创建了div1,其中的所有内容都附加了1(变量)。表单元素相互依赖,并由ID调用。问题是,当我创建一个新div并且变量(i)更改为2时,第一组表单元素尝试使用2而不是1。
有意义吗?
编辑:这是一些代码。这太乱了,所以我提前道歉。
var i = 0;
$('a#add-product').click(function(event){
i++;
$('<div />').addClass('product').attr('id', 'product'+i)
.append($('<h2><img src="<?php echo base_url();?>img/product.png" alt="" />Product '+i+'</h2>'))
.append($('<div class="info-line"><label>Division</label><p><select id="selection-'+i+'" class="selection"><option value="">- Select a Division -</option><option value="abrasives">Abrasives</option><option value="tapes">Bonding, Surface Protection & Tapes</option><option value="packaging">Packaging</option></select></p></div>'))
.append($('<div class="info-line"><label>Category</label><p><select id="selectionresult-'+i+'" name="selectionresult-'+i+'" class="selectionresult"></select><span id="result-'+i+'" class="result"> </span></p></div>'))
.append($('<div class="info-line"><label>Product</label><p><select id="selectionresult2-'+i+'" name="selectionresult2-'+i+'" class="selectionresult2"></select><span id="result2-'+i+'" class="result2"> </span></p></div>'))
.append($('<a class="remove" href="#add-product" id="remove-product'+i+'"><img src="<?php echo base_url();?>img/remove-product.jpg" alt="" />Remove Product</a>'))
.appendTo("#products");
// START OF ADDITIONAL PRODUCT DROP DOWNS
$("#selectionresult-"+i).hide();
$("#selectionresult2-"+i).hide();
$("#selection-"+i).change( function() {
$(this).next(".selectionresult").hide();
$(this).next(".selectionresult2").hide();
$("#result-"+i).html('Retrieving ...');
$.ajax({
type: "POST",
data: "data=" + $(this).val(),
url: "<?php echo base_url();?>dropdown.php",
success: function(msg){
if (msg != ''){
$("#selectionresult-"+i).html(msg).show();
$("#result-"+i).html('');
}
else{
$("#result-"+i).html('<em>No item result</em>');
}
}
});
});
$("#selectionresult-"+i).change( function() {
$(this).next(".selectionresult2").hide();
$("#result2-"+i).html('Retrieving ...');
$.ajax({
type: "POST",
data: "data=" + $(this).val(),
url: "<?php echo base_url();?>dropdown.php",
success: function(msg){
if (msg != ''){
$("#selectionresult2-"+i).html(msg).show();
$("#result2-"+i).html('');
}
else{
$("#result2-"+i).html('<em>No item result</em>');
}
}
});
});
});
答案 0 :(得分:2)
您可以将需要引用正确版本i
的代码放在这样的闭包中:
var i = 0;
$('a#add-product').click(function(event){
i++;
// Begin closure. When called (at the end of the closure) it receives
// the current value of "i". This value of "i" will be referenced
// throughout the closure as a local variable containing the value
// you expect, instead of the "shared" "i" variable outside the
// closure.
(function( i ) {
// So basically we've created a new "scope" inside here. Now "i"
// is a separate local variable than the "i" variable ouside
// the closure. You could change the variable name by changing
// the parameter above. Like (function( my_i ) {...
// If you did that, you would need to change the "i" in your .change()
// handlers to "my_i". The rest of them could stay the same, or you
// could change them. Either way would work.
// This is because the .change() handlers are executed at a later time
// (and so are the AJAX callbacks) so they need to use the variable
// that is local to this closure.
// The rest of the code, like $("#selectionresult-" + i) is executing
// immediately, so it could reference the "i" variable that is
// outside the closure, and still work properly.
$('<div />').addClass('product').attr('id', 'product'+i)
.append($('<h2><img src="<?php echo base_url();?>img/product.png" alt="" />Product '+i+'</h2>'))
.append($('<div class="info-line"><label>Division</label><p><select id="selection-'+i+'" class="selection"><option value="">- Select a Division -</option><option value="abrasives">Abrasives</option><option value="tapes">Bonding, Surface Protection & Tapes</option><option value="packaging">Packaging</option></select></p></div>'))
.append($('<div class="info-line"><label>Category</label><p><select id="selectionresult-'+i+'" name="selectionresult-'+i+'" class="selectionresult"></select><span id="result-'+i+'" class="result"> </span></p></div>'))
.append($('<div class="info-line"><label>Product</label><p><select id="selectionresult2-'+i+'" name="selectionresult2-'+i+'" class="selectionresult2"></select><span id="result2-'+i+'" class="result2"> </span></p></div>'))
.append($('<a class="remove" href="#add-product" id="remove-product'+i+'"><img src="<?php echo base_url();?>img/remove-product.jpg" alt="" />Remove Product</a>'))
.appendTo("#products");
// START OF ADDITIONAL PRODUCT DROP DOWNS
$("#selectionresult-" + i).hide();
$("#selectionresult2-" + i).hide();
$("#selection-" + i).change(function () {
$(this).next(".selectionresult").hide();
$(this).next(".selectionresult2").hide();
$("#result-" + i).html('Retrieving ...');
$.ajax({
type: "POST",
data: "data=" + $(this).val(),
url: "<?php echo base_url();?>dropdown.php",
success: function (msg) {
if (msg != '') {
$("#selectionresult-" + i).html(msg).show();
$("#result-" + i).html('');
}
else {
$("#result-" + i).html('<em>No item result</em>');
}
}
});
});
$("#selectionresult-" + i).change(function () {
$(this).next(".selectionresult2").hide();
$("#result2-" + i).html('Retrieving ...');
$.ajax({
type: "POST",
data: "data=" + $(this).val(),
url: "<?php echo base_url();?>dropdown.php",
success: function (msg) {
if (msg != '') {
$("#selectionresult2-" + i).html(msg).show();
$("#result2-" + i).html('');
}
else {
$("#result2-" + i).html('<em>No item result</em>');
}
}
});
});
// End closure. Executes the closure function, passing in the
// current value of "i"
})( i );
});
修改强>
为了解释发生了什么,在javascript中,传递给(或创建)函数体的变量是该函数的本地变量,并且它们仍然存在。
我上面所做的就是创建一个接受一个参数的函数。在这里,我将更改参数的名称,以使其更清晰:
function( inner_i ) {
// create your element with the new local variable "inner_i"
}
...但是我创建它之后我也调用该函数:
(function( inner_i ) {
// create your element with the new local variable "inner_i"
})( i )
// ^------- call the function, passing in the "i" from your loop.
语法看起来有点奇怪,但它只是一种调用你刚刚创建的函数的方法。
这与做:
相同function myNewFunction( inner_i ) {
// creates your element with the new local variable "inner_i"
}
myNewFunction( i ); // Call the function we just created above,
// and pass the "i" from the loop into it
答案 1 :(得分:0)
使用单独的变量存储索引,使用循环添加到它。
粗略地说,循环函数(无论是否调用带索引号的另一个函数都是无关紧要的),但这样你就可以得到索引值,并使用你的循环,所以没有重复。
var uniqueIndex = 0;
function functionWithLoop(x)
{
for (i=0; i<x; i++)
{
uniqueIndex++;
createNewDivFunction(uniqueIndex);
}
}
答案 2 :(得分:0)
根据我的理解,div1中的元素互相引用但不是div2中的元素。问题是,他们如何互相引用?如果是事件,例如文本框的onchange事件,则可以执行以下操作:
var MAX = 10;
for (var i = 0; i < MAX; i++) {
// Create textbox
$("<input type='text'>").attr("name", "slave" + i);
// Create a second textbox that, when changed, takes it's value,
// makes it uppercase, and copies it to the first one
$("<input type='text'>").attr("name", "master" + i)
.change(
(function(i) {
function() {
$("input[name=slave" + i + "]").text($(this).text());
}
})(i)
);
}
它的作用是创建一个临时范围,用于捕获i
本身的值:
(function(i) {
function() {
// the value of i is frozen in time within here
}
})(i)
答案 3 :(得分:0)
实际上,更简单的答案是将整数存储为您正在创建的每个元素的值。使您免于弄乱闭包,并且更易于维护。在你的循环中,只需:
newElement.data("myIndex", i);
再次检索索引:
newElement.data("myIndex");
或者,如果在事件处理程序中:
$(this).data("myIndex");