use*_*993 1 html javascript jquery
我有以下HTML结构:
<div id="blah">
<ul style="...">
<li><a href="...">...</a></li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
我有一个针对所有<a>标签的jQuery选择器.但是,我想检查点击<a>是否是一个子项目id="blah".
这是我到目前为止:
$(document).on('click', 'a', function(t) {
console.info($(this).text());
if($(this).parent() == 'blah'){
console.info('Yes, this link has the parent');
}
});
Run Code Online (Sandbox Code Playgroud)
但是,if永远不会变为真,我无法检测链接何时具有指定的父级.我该如何正确地做到这一点?
使用attr()来获取元素的属性值
if($(this).parent() == 'blah'){
Run Code Online (Sandbox Code Playgroud)
应该
if($(this).parent().attr('id') == 'blah'){
Run Code Online (Sandbox Code Playgroud)
$(document).on('click', 'a', function() {
console.info($(this).text());
if ($(this).parent().attr('id') == 'blah') {
console.info('Yes, this link has the parent');
}
return false; // To stop page redirection
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blah">
<ul style="...">
<li><a href="...">...</a>
</li>
</ul>
</div>Run Code Online (Sandbox Code Playgroud)
你也可以使用
if($(this).parent().is('#blah'){
Run Code Online (Sandbox Code Playgroud)
我想检查点击是否是id ="blah"的子项.
if ($(this).parent('#blah').length) {
Run Code Online (Sandbox Code Playgroud)
如果要检查,这将检查直接父母 祖先
if ($(this).closest('#blah').length) {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |