[英]Creating and linking dynamic elements simultaneously
我正在创建两个元素:foo和bar,我需要同时链接它们。
<div class="target-1"></div>
<div class="target-2"></div>
<form>
<input type="text" />
<button type="submit">Submit</button>
</form>
这些是所创建元素的目标。 现在这是js:
var index = 0;
$("form").submit(function(){
$(".target-1").append(
$("<span/>", {class: "foo", id: "s-" + index++}));
$(".target-2").append(
$("<span/>", {class: "bar s-" + index}));
});
现在,这是要在id-1的target-1内创建一个span.foo,同时在target-2的类sn内创建另一个span.bar,其类与id完全相同。 span.foo。
它实际上所做的是创建span.foo id =“ s-0”和span.bar class =“ s-1”。 我不明白为什么,因为我要在第一个追加中增加索引,然后在第二个追加中设置索引的当前状态。
这是一个小提琴http://jsfiddle.net/Yrrfd/,但是我只使用按钮而不使用任何表单,因为您不能在jsfiddle中提交表单。 但是它应该可以正常工作,并且无论如何您都可以看到不同的索引值。
您要在分配后增加索引,您需要使用++index
而不是index++
$(".target-1").append(
$("<span/>", {class: "foo", id: "s-" + ++index})); // Here
$(".target-2").append(
$("<span/>", {class: "bar s-" + index}))
});
后递增运算符将首先分配,然后再递增。 您需要预增量运算符。
您应该使用++index
而不是index++
。
index++
为您提供值,然后将其递增。 ++index
递增,然后为您提供值。
您应该使用++index
,以使索引递增然后使用。 这是更新的小提琴: http : //jsfiddle.net/Yrrfd/5/
我不确定我是否100%理解您的要求,但是我认为您需要将其更改为
var index = 0;
$("form").submit(function(){
$(".target-1").append(
$("<span/>", {class: "foo", id: "s-" + index}));
$(".target-2").append(
$("<span/>", {class: "bar s-" + index}));
index++;
});
要么
var index = 0;
$("form").submit(function(){
index++;
$(".target-1").append(
$("<span/>", {class: "foo", id: "s-" + index}));
$(".target-2").append(
$("<span/>", {class: "bar s-" + index}));
});
第一次索引值是(0)和index ++(首先使用,然后递增),因此它将用作0,然后递增1,然后继续显示bar,现在为1。
var index = 0;
$("form").submit(function(){
$(".target-1").append(
$("<span/>", {class: "foo", id: "s-" + index}));
$(".target-2").append(
$("<span/>", {class: "bar s-" + index++}));
});
因此,您需要在bar append函数处增加索引变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.