同时创建和链接动态元素

Creating and linking dynamic elements simultaneously

本文关键字:动态 元素 链接 创建      更新时间:2023-09-26

我正在创建两个元素: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}));
});

现在这意味着创建一个span。target-1中的Foo, id为"s-n",同时创建另一个span。target-2内的Bar,类"s-n"与span.foo的id完全相同。

它实际做的是创建span。Foo id="s-0"和span。酒吧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++给出该值,然后将其加1。++index增加它,然后给你的值。

您应该使用++index,以便索引是递增的,然后使用。这是更新后的小提琴:http://jsfiddle.net/Yrrfd/5/

我不确定我完全理解你的要求,但我认为你需要把它改成

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++(第一次使用然后递增),所以它将使用as 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函数