cbr*_*ake 4 html jquery-mobile
我无法从列表项中获取点击事件.在此页面中:
http://bec-systems.com/list-click.html
列表中的第一个条目触发单击事件.但是,如果我通过按"刷新更新列表"按钮动态添加3个事件,则接下来的3个列表条目不会生成单击事件.
感谢关于如何使这项工作或通常改进代码的任何建议.
谢谢,克利夫
代码也列在下面:
<!DOCTYPE html>
<html>
<head>
<title>Status</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#refreshUpdateButton").on("click", function(event, ui) {
console.log("refreshUpdateButton")
versions = ["0.3", "0.4", "0.5"]
for (var i=0; i < versions.length; i += 1) {
$("#updateVersionsList").append('<li><a id="updateVersionItem-' + (i+3) + '">' + versions[i] + '</a></li>');
if ($("#updateVersionsList").hasClass('ui-listview')) {
$("#updateVersionsList").listview("refresh");
} else {
$("#updateVersionsList").trigger('create');
}
}
})
$('[id^=updateVersionItem]').on("click", function(event, ui) {
console.log("updateVersion, selected = " + $(this).attr('id'));
})
});
</script>
</head>
<body>
<!-- Software update page -->
<div data-role="page" id="software-update-page">
<div data-role="header">
<h1>Software Update</h1>
</div><!-- /header -->
<div data-role="content">
<h1>Select Software version:</h1>
<ul data-role="listview" id="updateVersionsList">
<li><a id="updateVersionItem-0">0.0</a></li>
<li><a id="updateVersionItem-1">0.1</a></li>
<li><a id="updateVersionItem-2">0.2</a></li>
</ul>
<br>
<a data-role="button" class="ui-btn-left" id="refreshUpdateButton">Refresh Update list</a>
</div><!-- /content -->
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
使用此形式.on()(以下评论).
$(document).on("click", '[id^=updateVersionItem]', function(event, ui) {
console.log("updateVersion, selected = " + $(this).attr('id'));
})
Run Code Online (Sandbox Code Playgroud)
示例:http://jsfiddle.net/saluce/YaAEJ/
否则,无论何时动态添加新元素,都需要将click事件附加到这些项目.
假设以下代码:
function doThisOnClick(event, ui) {
console.log("updateVersion, selected = " + $(this).attr('id'));
}
$('[id^=updateVersionItem]').on("click", doThisOnClick);
Run Code Online (Sandbox Code Playgroud)
您可以取消绑定处理程序并重新附加到所有匹配项:
$('[id^=updateVersionItem]').off("click", doThisOnClick);
$('[id^=updateVersionItem]').on("click", doThisOnClick);
Run Code Online (Sandbox Code Playgroud)
或者只需在添加后将其动态添加到新项目中:
$("#updateVersionsList").append('<li><a id="updateVersionItem-' + (i+3) + '">' + versions[i] + '</a></li>').on("click", doThisOnClick);
Run Code Online (Sandbox Code Playgroud)