【问题标题】:How should jquery .after work in this situation?jquery .after 在这种情况下应该如何工作?
【发布时间】:2013-09-11 17:55:10
【问题描述】:

我不知道我是否错误地使用了 .after,但我的理解是它应该在我指定的元素之后显示元素? - Option1 选择后的 hello world 选择框?

<select id="cselect" >
<option value="Option 1">Option 1</option>

</select>

$('#cselect').chosen();

var test = '<select id="dselect" ><option>Hello World</option></select>';  

$('#cselect').after(test);

$('#dselect').chosen();

在这里摆弄 - http://jsfiddle.net/jHvmg/4/

我错过了什么? TIA

【问题讨论】:

  • 您的示例代码和 jsFiddle 缺少 &gt; ...orld&lt;/option&lt;/selc...
  • @phuzi 已修复,谢谢,但似乎并没有解决问题。

标签: jquery jquery-chosen


【解决方案1】:

这与选择的插件有关。当您第一次在第一个 select 上调用 chosen 时,您最终会得到这个(伪代码):

<select id="select1"></select>
<div id="chosenForSelect1"></div>

添加新的select 后,您将拥有:

<select id="select1"></select>
<select id="select2"></select>
<div id="chosenForSelect1"></div>

然后您在第二个select 上调用.chosen() 并得到以下结果:

<select id="select1"></select>
<select id="select2"></select>
<div id="chosenForSelect2"></div>
<div id="chosenForSelect1"></div>

所以实际的select 元素是在第一个元素之后添加的,但是支持所选插件的divs 不正常。最好将新的select 附加到容器中,为每个select 添加一个容器,或者在所选插件的 html 之后附加。

【讨论】:

  • 所有答案都可以,但这个对我来说效果最好,因为我正在根据第一个选择加载第二个选择。谢谢大家的回复!!!
【解决方案2】:

.after() 在匹配元素集中的每个元素之后插入由参数指定的内容。您正在以正确的方式使用它。检查使用上述代码创建的 DOM 顺序。你可以看到body标签内的第一个HTML元素是:

<select id="cselect" style="display: none;">
    <option value="Option 1">Option 1</option>
</select>

第二个是:

<select id="dselect" style="display: none;"><option>Hello World</option></select>

根据选择创建div's 动态更改顺序。

解决方案:一旦你使用 .after 将动态 html 代码添加到 DOM 中,在 select 上选择如下:

var test = '<select id="dselect" ><option>Hello World</option</select>';  

$('#cselect').after(test);
 $('#cselect').chosen();
$('#dselect').chosen();

DEMO FIDDLE

【讨论】:

    【解决方案3】:

    如果您查看插件生成的 HTML,它实际上隐藏了选择并在其后添加了一个 div,这是实际呈现的选择。

    所以你最终得到的是:

    <select id="cselect" style="display: none;">
        <option value="Option 1">Option 1</option>
    </select>
    <select id="dselect" style="display: none;">
        <option>Hello World</option>
    </select>
    <div class="chosen-container chosen-container-single" style="width: 94px;" title="" id="dselect_chosen"> ... </div>
    <div class="chosen-container chosen-container-single" style="width: 76px;" title="" id="cselect_chosen"> ... </div>
    

    你实际上最终在 cselect 之前插入了 dselect。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2018-06-16
      • 2017-06-21
      • 2018-01-19
      相关资源
      最近更新 更多