基本的jQuery问题

时间:2010-12-10 09:11:36

标签: javascript jquery javascript-events

我现在很长时间都在讨论jQuery。它非常强大,我们可以用jQuery做很多很棒的事情。

我的问题是我同时使用了很多jQuery功能。例如。我有一个显示项目的站点,每页12个项目,我可以使用jquery在页面中分页。在同一页面上,我实现了一个使用jQuery的thumpsUp按钮。

我使用的jQuery功能越多,就越难以正确地安排它们。 E.g:

$(document).ready(function() {
 $(".cornerize").corner("5px"); //cornerize links
 $('a#verd').live('click', exSite); //open iframe
 $("a.tp").live('click', thumpsUp); //thumps up
 $("a#next").click(getProgramms); //next page
 $("a#previous").click(getProgramms); //previous page
    //for the current page reload the content
 $("a#page").each(function() {
  $(this).click(getProgramms);
 });
 //this isn't working...
 $('.smallerpost').live('click', alert('test'));
});

查看最后一个代码行。我想在单击div元素时执行警报。当我刷新页面时,页面会显示警报,而不是这样做。单击div无效。

我做错了什么?这里有一个干净且有效的jQuery策略是什么?

2 个答案:

答案 0 :(得分:3)

将该行更改为

$('.smallerpost').live('click', function () {
    alert('test');
});

当你在那里时......

$("a#page").each(function() {
    $(this).click(getProgramms);
});

具有与以下完全相同的效果:

$('a#page').click(getProgramms);

...但从技术上讲,只有一个元素id ='page'无论如何

答案 1 :(得分:0)

您的代码$('.smallerpost').live('click', alert('test'));立即调用alert并将其返回值作为第二个参数传递给live函数。你要传递的是一个要调用的函数,所以你想要:

$('.smallerpost').live('click', function() {
    alert('test');
});

$('.smallerpost').live('click', handleSmallerPostClick);

function handleSmallerPostClick() {
    alert('test');
}

...取决于您如何构建代码。