[英]Append stylesheet link for printing triggered on jQuery click() event
[英]click event not triggered on my link, how to fix?
我正在基於接收到的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);
}
});
我的問題是,創建的鏈接不會在click事件上觸發。
作為測試,我在頁面上手動創建了一個鏈接ID,其鏈接ID與其他鏈接的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>
問題是您是在添加鏈接之前添加onClick的,因為鏈接是在ajax返回之后一段時間(異步)添加的。 最簡單的解決方案是在populateCourses方法中添加點擊:
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);
$("a[id^=id]").on("click", function(event) {
alert('here');
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.