为什么这个jQuery选择器不起作用?

5

我收到了客户的任务,需要修正一个页面,但是我发现jQuery后代选择器的行为与预期不同。

以下是HTML代码片段:

<form action="http://submit.url/subscribe.php" method="post" enctype="multipart/form-data" id="mssysform8217" class="mssysform" >
<div id="mssys-formcontainer">
    <div class="formfields">
        <table style="width: 100%">
        <div class="formfield-item" id="formfield-item-email">
            <tr>
            <td class="style1"><label >E-mail címe</label></td>
            <td>
                <input type="text" name="email" value="">
                <div class="error-container">Please fill in this field!</div>
                <div style="clear: both;"></div>
            </td>
            </tr>
        </div>
        </table>
    </div>
</div>
</form>

我尝试使用FireFox进行调试:
  • this worked:

    console.debug($("#mssysform8217 :input[name='email']").val());
    

    test@gmail.com

  • this did not worked:

    console.debug($("#mssysform8217 #formfield-item-email :input[name='email']").val());
    

    undefined

  • but:

    console.debug($("#mssysform8217 #formfield-item-email"));
    

    [div#formfield-item-email.formfield-item]

问题在于提交脚本是由第三方应用程序生成的,它希望使用3级后代选择器。

你为什么要使用多个ID选择器(“#id”)? - Homer
似乎只有一个<input>从#formfield-item-email下降,因此[name]属性选择器是不必要的。 $('#formfield-item-email input').val()应该是你所需要的。 - stevelove
1个回答

16

您尝试使用的jQuery选择器将无法工作,因为HTML无效。

<table style="width: 100%">
        <div class="formfield-item" id="formfield-item-email">
            <tr>

这不是有效的HTML。在表格中间放置除了<thead><tfoot><tbody><tr>以外的任何元素(包括

)都是无效的。

以下是有效的:

<div>
  <table>
    <tr><td></td></tr>
  </table>
</div>

或者这样也是有效的:

<table>
  <tr><td><div></div></td></tr>
</table>

顺便说一下:你正在使用表格来格式化你的表单。表格是用于制作表格数据的,仅仅是为了布局而使用表格不是一个好主意。在HTML元素中使用适当的语义(例如:表格=表格数据,li=列表,div=页面分割等)。


1
“在表格中间放置 div(或任何元素)是无效的……” 例外情况是 <thead><tbody> - user113716
th不能直接放入表中,它是一个表头“单元格”,应始终位于tr内。尽管如此还是加1分。 - GolezTrol
谢谢。该表格也是由第三方应用程序自动生成的,我不确定div的位置是否允许在那里。 - sipiatti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接