【问题标题】:jQuery select p inside thisjQuery 在这个里面选择 p
【发布时间】:2013-04-05 12:35:30
【问题描述】:

在点击的ID里面选择p标签有问题,代码如下;

<tbody>
    <tr id="test1">
    <p>
        Some random text that should show up in the dialog.
    </p>
        <td>test</td>
        <td>test</td>
    </tr>
    ... the rest of the tr's are identical, nothing else to see here.
 </tbody>


$('#test1, #test2, #test3, #test4').click(function(){
    $(this 'p').dialog();
});

现场测试; http://team-blandsaft.no-ip.org/

最好习惯在 stackoverflow 编辑器中编写一些代码。

【问题讨论】:

  • 离题:tr 元素应该只有 td 子元素。另外 $(this 'p') 甚至在语法上都不正确
  • 如果你把 HTML 放到一个页面中,p 将在构建 DOM 时移动到其他地方(因为它不是 tr 的有效子代):demonstration JS Fiddle。

标签: jquery html jquery-ui jquery-selectors


【解决方案1】:

使用.find()

$(this).find('p').dialog();

或者您可以使用context selector

$('p',this).dialog(); 

内部使用 find 方法

正如其他人所提到的,您的 html 无效,&lt;p&gt; 作为 &lt;tr&gt; 的子级

来自MDN docs 为 tr

允许的内容:零个或多个 &lt;td&gt; 或 &lt;th&gt; 元素,或它们的混合

【讨论】:

  • 而且它 仍然 不起作用,因为 p 将被移到 table 元素之外,当构造 DOM 时,因为它是无效的html:JS Fiddle.
  • @initium,这不是打开 jquery UI 对话框.dialog('open')的语法吗?
  • @initium 您将不得不将那些p 元素从您的table 中提取出来,因为它是无效的HTML(或者将它们放在td 中)。如果你把他们从你的桌子上拉出来,你可以给他们一个班级,然后选择那个班级来激活你的对话:$('.dialog-class').dialog();。这样,您就不必依赖 table 来选择哪些元素会变成对话框。
【解决方案2】:
$('#test1, #test2, #test3, #test4').click(function(){
    $(this).children('p').dialog();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-27
    • 2011-07-11
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    相关资源
    最近更新 更多