动态添加元素的点击事件
click event on dynamically added elements
我几乎阅读了我能找到的所有内容,但我找不到解决问题的办法。
$('.list-item').on('click', 'p', function(){
$(this).next('.list-item small').toggle();
});
如果我输入一个 id 而不是 $('.list-item').on('click...'
,则此代码可以正常工作,例如$('#someid').on('click...'
而且我不知道为什么或如何让我的代码工作
这是我的 HTML
<ul>
<li class="list-item">
<p>sometext</p>
<small>sometext</small>
</li>
<li class="list-item">
<p>sometext</p>
<small>sometext</small>
</li>
<li class="list-item">
<p>sometext</p>
<small>sometext</small>
</li>
</ul>
$('.list-item').on('click', 'p', function(){
$(this).next('.list-item.small').toggle();
});
可能会有帮助
您需要在页面加载时获取现有元素,在此示例中
ul
元素,试试这个。
$(document).ready(function(){
$(function(){
$("input").on("click", function(){
$("ul").append('<li class="list-item">\
<p>sometext</p>\
<small>sometext</small>\
</li>');
});
});
$(function(){
$('ul').on('click', 'li p', function(){
$(this).next('.list-item small').toggle();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="button" value="Click me!">
<ul>
<li class="list-item">
<p>sometext</p>
<small>sometext</small>
</li>
</ul>
我几乎阅读了我能找到的所有内容,但我找不到解决问题的办法。
$('.list-item').on('click', 'p', function(){
$(this).next('.list-item small').toggle();
});
如果我输入一个 id 而不是 $('.list-item').on('click...'
,则此代码可以正常工作,例如$('#someid').on('click...'
而且我不知道为什么或如何让我的代码工作
这是我的 HTML
<ul>
<li class="list-item">
<p>sometext</p>
<small>sometext</small>
</li>
<li class="list-item">
<p>sometext</p>
<small>sometext</small>
</li>
<li class="list-item">
<p>sometext</p>
<small>sometext</small>
</li>
</ul>
$('.list-item').on('click', 'p', function(){
$(this).next('.list-item.small').toggle();
});
可能会有帮助
您需要在页面加载时获取现有元素,在此示例中
ul
元素,试试这个。
$(document).ready(function(){
$(function(){
$("input").on("click", function(){
$("ul").append('<li class="list-item">\
<p>sometext</p>\
<small>sometext</small>\
</li>');
});
});
$(function(){
$('ul').on('click', 'li p', function(){
$(this).next('.list-item small').toggle();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="button" value="Click me!">
<ul>
<li class="list-item">
<p>sometext</p>
<small>sometext</small>
</li>
</ul>