以下是我的代码:
<div class="sidebar-list">
<h4>Type</h4>
<ul>
<li><a href="#" id='shop'> Shop</a></li>
<li><a href="#" id='food'> Food</a></li>
<li><a href="#" id='beauty'> Beauty</a></li>
<li><a href="#" id='comfort'>Comfort</a></li>
<li><a href="#" id='health'> Health</a></li>
<li><a href="#" id='pet'> Pet</a></li>
<li><a href="#" id='fun'> Fun</a></li>
<li><a href="#" id='life'> Life</a></li>
</ul>
</div>
我知道我可以写每个li项目,但是任何聪明的方式添加事件监听侧边栏列表的监听列表项都会被点击并获得它的价值吗?
答案 0 :(得分:4)
尝试:
$('ul').delegate('a', 'click', function() {
// ... your code ...
});
&#13;
$('.sidebar-list').on('click', 'li', function() {
alert($(this).text());
});
&#13;
答案 1 :(得分:0)
shared_ptr.get()
答案 2 :(得分:0)
$('.sidebar-list li').click(function(){
alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar-list">
<h4>Type</h4>
<ul>
<li><a href="#" id='shop'> Shop</a></li>
<li><a href="#" id='food'> Food</a></li>
<li><a href="#" id='beauty'> Beauty</a></li>
<li><a href="#" id='comfort'>Comfort</a></li>
<li><a href="#" id='health'> Health</a></li>
<li><a href="#" id='pet'> Pet</a></li>
<li><a href="#" id='fun'> Fun</a></li>
<li><a href="#" id='life'> Life</a></li>
</ul>
</div>
答案 3 :(得分:0)
var div = document.querySelector(".sidebar-list"),
addEvent = ( obj, type, fn ) => {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
};
addEvent(div, "click", (ev) => {
var event = ev || window.event;
target = event.target || event.srcElement;
// do something with your target
});
如果页面中尚未使用jQuery,则不需要jQuery(请注意,polyfill来自jQuery的作者...)