这是我的代码:
<div class="superBlock" id="blabla">
<a class="watch"><img src="images/blabla.png"/></a>
</br>
<div class="btn-group-xs" role="group">
<a type="button" class="btn btn-info info" data-toggle="modal" data-target="#myModal">Information</a>
</div>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-footer">
<a type="button" class="btn btn-success watch" data-dismiss="modal">Watch</a>
</div>
</div>
</div>
</div>
$('.info').click(function() {
var $watchID = $(this).parents('.superBlock').attr('id');
});
$('.watch').click(function() {
if($(this).parents('.superBlock').attr('id') != "") {
var $watchID = $(this).parents('.superBlock').attr('id');
}
alert($watchID);
});
我想做的是将 $watchID 设置为 .superBlock 的 ID,无论我是单击 .watch 按钮还是 .info 按钮。
当我在单击信息按钮后单击模式监视按钮时,我得到 $watchID
is "undefined"。
如果 $(this).parents('.superBlock').attr('id ')
未定义。所以 $watchID
不要更改为未定义的 $(this).parents('.superBlock').attr('id')
。
我该怎么办?这只是关于语法吗?如果是这样,我应该如何更改它?
这个 HTML div 重复使用不同的 ID,这就是为什么我不能只将 ID 设置为“blabla”。
最佳答案
要判断选择器是否匹配任何内容,请检查 jQuery 对象的长度。
var superblock = $(this).closest(".superBlock");
if (superblock.length > 0) {
$watchID = superblock.attr('id');
}
此外,如果您希望 $watchID
变量在调用之间保持不变,则应在函数外部声明它。您的变量是每个函数的局部变量,因此当函数返回时它会被丢弃。
因为您只想要与该类最近的父级,请使用 .closest()
而不是 .parents()
,它会在整个 DOM 层次结构中搜索多个匹配项.
关于javascript - 仅当 parents ('.class' ).attr ('id' ) 存在时如何定义 $var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39626712/