JQuery - 无法按类选择动态创建的 URL 标记
因此,我正在为我的网站创建 TagCloud,但在使用 JQuery 提醒我所选链接时遇到问题。 该网站很好地创建了链接,为它们提供了“tagLink”类,但是当我尝试提醒具有该类的元素数量时,它给了我 0。 有什么想法吗? 这是我的代码:
$(function() {
//get tag feed
$.getJSON("tagcloud/tagcloud.php?callback=?", function(data) {
//create list for tag links
$("<ul>").attr("id", "tagList").appendTo("#tagCloud");
//create tags
$.each(data.tags, function(i, val) {
//create item
var li = $("<li>");
//create link
$("<a>").addClass('tagLink').text(val.tag).attr({title:"See all pages tagged with " + val.tag, href:"tags/" + val.tag + ".php", id: val.tag}).appendTo(li);
//set tag size
li.children().css("fontSize", (val.freq / 10 < 1) ? val.freq / 10 + 1 + "em": (val.freq / 10 > 2) ? "2em" : val.freq / 10 + "em");
//add to list
li.appendTo("#tagList");
});
});
//Increase database if link is clicked
alert($('.tagLink').size());//Test how many exist
$('.tagLink').click(function(){
var id = $(this).attr('id');
$.ajax({
url: "tagcloud/tagcloud.php",
type: "POST",
data: {clicked : id}
});
});
});
So I am creating a TagCloud for my site and am having issues being able to use JQuery to alert me of the selected link.
The site created the links just fine, gives them the class of 'tagLink', but when I try to alert the number of elements with that class, it gives me 0.
Any ideas??
Here is my code:
$(function() {
//get tag feed
$.getJSON("tagcloud/tagcloud.php?callback=?", function(data) {
//create list for tag links
$("<ul>").attr("id", "tagList").appendTo("#tagCloud");
//create tags
$.each(data.tags, function(i, val) {
//create item
var li = $("<li>");
//create link
$("<a>").addClass('tagLink').text(val.tag).attr({title:"See all pages tagged with " + val.tag, href:"tags/" + val.tag + ".php", id: val.tag}).appendTo(li);
//set tag size
li.children().css("fontSize", (val.freq / 10 < 1) ? val.freq / 10 + 1 + "em": (val.freq / 10 > 2) ? "2em" : val.freq / 10 + "em");
//add to list
li.appendTo("#tagList");
});
});
//Increase database if link is clicked
alert($('.tagLink').size());//Test how many exist
$('.tagLink').click(function(){
var id = $(this).attr('id');
$.ajax({
url: "tagcloud/tagcloud.php",
type: "POST",
data: {clicked : id}
});
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getJSON 是异步的,因此您的选择器会在添加标签链接之前运行。将标记链接点击处理程序分配移至 AJAX 回调内。
getJSON is asynchronous so your selector gets run before the tag links get added. Move the taglink click handler assignment inside your AJAX callback.
您可以使用 $.get() 或 $.ajax() 代替。
You can use $.get() or $.ajax() instead.