我正在基于我收到的 JSON 数据在 FLY 上创建几个链接(使用 jQuery html 函数)。每个链接都有 id“idxxxx”(xxxx 是主键)。
这是我正在使用的 JavaScript 代码:
$(document).ready(function(){
onLoad();
$("a[id^=id]").on("click", function(event) {
alert('here');
});
function onLoad() {
$(document).prop("title", "Course Listing");
getCourses();
}
function getCourses(name) {
$.ajax({
url: "http://localhost/courses/getCourses?format=json"
, dataType: "json"
, data: {name: name}
, success: function(data, status) {
populateCourses(data);
}
});
}
function populateCourses(data) {
var html = "";
if (data.length > 0) {
$.each(data, function () {
html += "<a href='##' id='id" + this.ID + "'>Edit</a><br />";
});
}
$("#courselist").html(html);
}
});
我的问题是创建的链接不会触发点击事件。
作为测试,我在页面上手动创建了一个链接标记,其 ID 与其他链接类似,但我没有遇到同样的问题。警报框显示正常。
关于如何解决这个问题有什么想法吗?谢谢
最佳答案
试试这个:
$(function() {
var ar = [];
for (var i = 1; i <= 10; i++) {
ar.push("<a href='#' id='id" + i + "'>Link " + i + " </a>");
}
$("#courselist").html(ar.join(''));
//THIS WILL ADD CLICK HANDLER TO ANY A INSIDE div#courselist
//EVEN IF IT IS ADDED AT RUNTIME
$("#courselist").on("click", "a[id^='id']", function(event) {
$("#log").append($("<span/>").text($(this).text()));
});
});
a {
margin: 2px;
padding: 3px;
outline: none;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="courselist"></div>
<div id="log"></div>
关于javascript - 我的链接未触发点击事件,如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27537475/