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

标签 jquery html jquery-selectors

我有一个来自客户的任务来更正一个页面,我发现 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 调试它:

  • 这有效:

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

    test@gmail.com

  • 这没有用:

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

    未定义

  • 但是:

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

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

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

最佳答案

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

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

这不是有效的 HTML。将 div(或除 <thead><tfoot><tbody><tr> 以外的任何元素)放在单元格外的表格中间是无效的。

这是有效的:

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

或者这是有效的:

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

旁注:您正在使用表格来格式化表单。表格用于表格数据。在我看来,使用表格进行布局是个坏主意。对 HTML 元素使用适当的语义(tables = 表格数据、li=lists、div=page divisions,等等)。

关于jquery - 为什么这个 jquery 选择器不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4250461/

相关文章:

jquery - 当用户在 jquery 中按下 Enter 键时,将 <br/> 隐藏在文本框中

jquery - 按条件选择

javascript - <tr> 元素删除()在第二次删除中不起作用

jquery - 将动态值添加到表标题下的下拉列表中

jquery - 如何在公共(public)函数中访问插件的用户定义选项?

javascript - 滚动到顶部不明显或裁剪顶部溢出

html - 如何制作溢出 :auto expand to the height of its contents up to a point? 的外部 div

html - Bootstrap,为什么位置:fixed shift the content & make the row not found?

html - 使用 css 从 ul 退出 "tab"

javascript - 制作一个 "Load More"按钮,显示我博客上的另外 2 篇文章