我有将点击事件绑定到ul li a
的代码。我想在点击时设置全局变量id
。首先console.log
返回1065,但第二个没有任何结果。如何在点击后获得全局id
?这是我的代码:
var id = 0;
$(function() {
var clickHandler = ('ontouchstart' in document.documentElement ? "touchstart" : "click");
$('ul li a').bind(clickHandler, function(e) {
var item = $(this).parent();
id = item[0].id;
console.log(id);
});
console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="sidebar-menu" id="nav-accordion">
<li id="1065">
<a class="active" href="#">
<i class="fa fa-dashboard"></i>
<span> Metrics</span>
</a>
</li>
</ul>