【问题标题】:How to create elements and select them on the fly with jQuery如何使用 jQuery 创建元素并动态选择它们
【发布时间】:2011-12-19 02:48:27
【问题描述】:

我对此有点困惑。我想创建一些元素(使用 jQuery),在该包装集上调用一个函数,并通过一个链继续这个过程几次。例如,

$('<div id="xxx"></div>')
  .call_plugin()
  .append('<div id="yyy"></div>')
  .call_plugin()
  .etc...
.end();

第一次调用插件影响 xxx,第二次影响 yyy,依此类推。但这并没有发生;我认为 call_plugin() 每次都在第一个 div (id=xxx) 上被调用。有解决办法吗?

提前致谢!

【问题讨论】:

  • .append() 实际上“粘贴” yyy insdes xxx,并返回新的 xxx。所以第二个 call_plugin 会影响新的 xxx。

标签: javascript jquery jquery-chaining


【解决方案1】:

再次调用 jQuery 让其他元素执行某些功能,并附加 .append:

$('<div id="xxx"></div>')
  .call_plugin()
  .append(
     $('<div id="yyy"></div>')
     .call_plugin()
  );

你可以用同样的方式嵌套它们:

$('<div id="xxx"></div>')
  .call_plugin()
  .append(
     $('<div id="yyy"></div>')
     .call_plugin()
     .append(
        $('<div id="zzz"></div>')
        .call_plugin()
     )
  );

别忘了不要把;s 放在嵌套的appends 之后。

【讨论】:

    【解决方案2】:
    $('<div id="xxx"></div>')
      .call_plugin()
      .append('<div id="yyy"></div>')
      .find('#yyy') // added this. From now on the current selection is #yyy element
      .call_plugin(); // this will be called on #yyy
    

    .end() 方法(您在末尾使用)用于结束链中的当前选择,如果您想继续使用同一链的前一个选择...

    在你的例子中

    $('<div id="xxx"></div>')
      .call_plugin()
      .append('<div id="yyy"></div>')
      .find('#yyy') // added this. From now on the current selection is #yyy element
      .call_plugin() // called on #yyy
      .end() // this returns the selection to be #xxx
      .something()//something else that will be called on #xxx
    

    【讨论】:

    • 这是一个艰难的决定。我认为这个答案更简单,但我无法让它发挥作用。 (也不代表错了!)+1,谢谢你的回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 2012-10-21
    • 2017-08-02
    相关资源
    最近更新 更多