gar*_*man 8 javascript jquery dom
我一直对一个演示中的jQuery感到有些沮丧,我正在打算一起,并且想知道以下是否只是jQuery的选择器和搜索方法的限制,或者我只是错误地使用它.
这是一个示例HTML块:
<div class='div_item'>
<td class='list'>
<dl><dt class="access_text">Div1 text1</dt></dl>
<dl><dt class="access_text">Div1 text2</dt></dl>
<dl><dt class="access_text">Div1 text3</dt></dl>
</td>
</div>
<div class='div_item'>
<td class='list'>
<dl><dt class="access_text">Div2 text1</dt></dl>
<dl><dt class="access_text">Div2 text2</dt></dl>
<dl><dt class="access_text">Div2 text3</dt></dl>
</td>
</div>
Run Code Online (Sandbox Code Playgroud)
这是jQuery 1.9.2脚本:
$().ready(function(){
$('.div_item'); // this is a 2 jQuery array, with no children
$('.div_item').find('.access_text'); // This is empty, length 0, .div_item's children aren't populated. Like I was using .children()
$('.div_item').find('.access_text').each(function() { // This doesn't work because the .div_item children aren't populated?
alert($(this).innerText);
}):
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,有没有理由为什么$('.div_item')数组对象中的子节点没有填充?如果它们没有填充,则无法引用它们,因此无法.find()正确编辑.这是我认为我的用法是问题的地方.
到目前为止,我看到的所有建议都适用于更平坦的DOM.例如<div class='div_item'><dt class="access_text"></dt></div>,但不是针对进一步嵌套的东西.
Did*_*hys 10
那你的代码不是很正确..find()不希望函数作为参数,而是期望选择器,jquery对象或DOM元素.
在thisfind方法中查看回调内的值,它指的是文档,而不是您<div>所期望的.
这是一个正确的代码:
$(document).ready(function(){
// cannot use .children() because the <dt> are not direct children
$('.div_item').find('.access_text').each(function() {
alert(this.innerText);
});
});
Run Code Online (Sandbox Code Playgroud)
好的!!!如果有人好奇并认为我一直疯了,请尝试自己测试一下。上面的 jQuery + 带有包装标签的更新的 HTML 示例!
我正在测试表中的 div,它可能在 DOM 解析中发现了一个缺口。我知道 div 不应该插入到它的元素之间,但我从没想过它会给我这样的惊喜!
这是 jQuery 查找失败的错误 html:(没有子元素)
<table>
<div class='div_item'>
<tr>
<td class='list'>
<dl><dt class="access_text">Div1 text1</dt></dl>
<dl><dt class="access_text">Div1 text2</dt></dl>
<dl><dt class="access_text">Div1 text3</dt></dl>
</td>
</tr>
</div>
</table>
Run Code Online (Sandbox Code Playgroud)
以下是我如何调整它以与 jQuery 一起使用:
<table>
<tr class='div_item'>
<td class='list'>
<dl><dt class="access_text">Div1 text1</dt></dl>
<dl><dt class="access_text">Div1 text2</dt></dl>
<dl><dt class="access_text">Div1 text3</dt></dl>
</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
现在可以通过查询找到 tr 类。在前一种情况下,div 的子级未填充,但 div 本身已返回。
非常棘手...
请注意,这是一个示例,改编自我的其他作品,因此如果有任何令人困惑的拼写错误,我深表歉意。
| 归档时间: |
|
| 查看次数: |
52491 次 |
| 最近记录: |