我有多种使用不同的输入名称和ID动态创建的表单。它们唯一具有的唯一特征是标签的内部HTML。是否可以通过带有jQuery的内部HTML标签选择输入?这是我的一个耐心的生日的例子,除了innerHTML之外,还有很多唯一的。

<div class="iphorm-element-spacer iphorm-element-spacer-text iphorm_1_8-element-spacer">
<label for="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">events=Object { mouseover=[1], mouseout=[1]}handle=function()data=Object { InFieldLabels={...}}
    Patient DOB
    <span class="iphorm-required">*</span>
</label>
<div class="iphorm-input-wrap iphorm-input-wrap-text iphorm_1_8-input-wrap">
    <input id="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8" class="iphorm-element-text iphorm_1_8" type="text" value="" name="iphorm_1_8">events=Object { focus=[1], blur=[1], keydown=[1], more...}handle=function()
</div>
<div class="iphorm-errors-wrap iphorm-hidden"> </div>




这是在Wordpress插件中,并且由于我们正在构建以允许员工编辑其站点(实际上是Wordpress网络),因此,如果可能,我们不想更改插件。
请注意,标签“ for”和输入“ id”共享相同的动态键,因此这可能是获取id的一种方式,但希望了解是否有更短的方法。

在这里,我清理了可能不使用的内容...

<div>
<label for="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">
    Patient DOB
    <span class="iphorm-required">*</span>
</label>
<div>
    <input id="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">
</div>

最佳答案

您可以使用contains selector选择Patient DOB标签,然后找到相关的输入。

$('label:contains("Patient DOB")').parent('div').find('input');


这假定labelinput包裹在同一div中,并且如果同一div中有多于一对,则可能不起作用。至少第一部分将为您提供包含Patient DOB的标签,然后您可以调整后面的部分以找到正确的输入元素。

有关jquery选择器的更多帮助,请参见API

这是fiddle演示的。

09-25 16:39
查看更多