Javascript 单击listview上动态生成的元素的事件
我尝试将单击事件应用于动态生成的元素 这个例子效果很好 但是我的代码不起作用 这是与上述链接相同的代码 HTMLJavascript 单击listview上动态生成的元素的事件,javascript,jquery,html,Javascript,Jquery,Html,我尝试将单击事件应用于动态生成的元素 这个例子效果很好 但是我的代码不起作用 这是与上述链接相同的代码 HTML 在…上 玩 在…上 玩 在…上 玩 JavaScript(Jquery) var计数器=0; $(“#添加按钮”)。单击(函数(){ $(“#控制台”).text('添加新行'); var text='新'+(++counter)+'播放'/li>'; $('#timer_listview')。前缀(文本); $('#timer_listview')。listvi
-
在…上
玩
-
在…上
玩
-
在…上
玩
JavaScript(Jquery)
var计数器=0;
$(“#添加按钮”)。单击(函数(){
$(“#控制台”).text('添加新行');
var text='新'+(++counter)+'播放'/li>';
$('#timer_listview')。前缀(文本);
$('#timer_listview')。listview(“刷新”);
});
var play=‘play’;
$('.timerList')。在('click','button',函数(){
$('控制台').text('单击');
var status=$(this.parent().find('span.status');
如果(status.text()==播放){
状态文本(“暂停”);
$('控制台').text('状态已更改');
}
});
CSS
.地位{
显示:无;}
我对它为什么不起作用感到恐慌(
谢谢你阅读我的问题
p、 It’欢迎随时编辑我的文章
更新 我解决了这个问题。 该点正在使用最近的父对象。
感谢Milind Anantwar。您正在动态添加元素
.timerList
。您需要使用:
$('#timer_listview').on('click', '.timerList', function() {
$('#console').text('clicked');
var status = $(this).parent().find('span.status');
if (status.text() == play) {
status.text('pause');
$('#console').text('Status Changed');
}});
功能点击按钮(e)
{
警报(e+“点击”);
}
按钮1
按钮2
按钮3
按钮4
谢谢您的回答。动态生成包含事件的元素时,我是否使用最高选择器?您应该使用保持静态的最近父级。@杰夫古康:很高兴它帮助我解决了这个问题。.多亏了Milind Anantwar。嗯,您能解释一下您的代码吗?
var counter = 0;
$('#addButton').click(function () {
$('#console').text('new line added');
var text = '<li class="timerList"><button>new' + (++counter) + '</button><span class="status">play</span></li>';
$('#timer_listview').prepend(text);
$('#timer_listview').listview("refresh");
});
var play = 'play';
$('.timerList').on('click', 'button', function () {
$('#console').text('clicked');
var status = $(this).parent().find('span.status');
if (status.text() == play) {
status.text('pause');
$('#console').text('Status Changed');
}
});
$('#timer_listview').on('click', '.timerList', function() {
$('#console').text('clicked');
var status = $(this).parent().find('span.status');
if (status.text() == play) {
status.text('pause');
$('#console').text('Status Changed');
}});
<script>
function onclickButton(e)
{
alert(e+"Clicked");
}
</script>
<button onclick="onclickButton(1)">Button1</button>
<button onclick="onclickButton(2)">Button2</button>
<button onclick="onclickButton(3)">Button3</button>
<button onclick="onclickButton(4)">Button4</button>