【问题标题】:load content with jquery ajax via dynamically generated buttons通过动态生成的按钮使用 jquery ajax 加载内容
【发布时间】:2013-04-05 14:13:06
【问题描述】:

我正在使用这个 Fiddle http://jsfiddle.net/wNDaG/ 中的代码,它会动态生成一些按钮。但是,我想做的是让每个按钮也执行通过 ajax 加载一些内容(将其附加到 div)的功能。

这是 Fiddle 的代码:

$('#tabs div').first().attr('class', 'current');

$('#tabs div').each(function(i) {
    i = i + 1;

$(this).attr('id', 'tab-' + i);

    if(i !== $('#tabs div').size()) {
    $(this).append('<button class="tabPagination" rel="tab-' + (i + 1) + '">Next</button>');
}
    if(i !== 1) {
    $(this).append('<button class="tabPagination" rel="tab-' + (i - 1) +    '">Previous</button>');
    }                
});            

$('#tabs div[class!="current"]').hide();

$('.tabPagination').live('click', function() {
    $('.current').removeAttr('class');
    $('#tabs div[class!="current"]').hide();
    $('#' + $(this).attr('rel')).show();
});

首先,我要做的第一件事是在附加按钮中添加类似这样的内容:

href="some-content/next-pagenum_' + (i + 1) + '"

在那之后,我需要帮助来组合如下函数,该函数将通过 ajax 附加内容:

$('.tabPagination').live('click', function(event) {
    var url = $(this).attr('href');
$('#content-target-div').load(url); // load the html into your chosen DOM element
    event.preventDefault(); // prevent the browser from navigating to this page  

    return false;
 });

这里的任何帮助将不胜感激。提前致谢!

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

    最简单的方法是执行以下操作:

    $.get(url, function(content) {
        $('#content-target-div').append(content);
    });
    

    代替

    $('#content-target-div').load(url);
    

    【讨论】:

    • 感谢安东尼的反馈。我是一个 JS 新手,所以请原谅我问的很明显,但是该代码会替换那一行还是整个函数?
    • 见上文 - 我已经回答了这个问题。谢谢!
    【解决方案2】:

    我设法使用以下代码解决了这个问题:

    $(document).on("click", ".tabPagination", function(){
        var link = $(this).attr('href');
    
        $('#ajaxcontent').fadeOut('fast', function() {
            $.get(
                link +' #ajaxcontent', 
                function(data) {
                    $("#ajaxcontent").html(data).fadeIn('fast');
                }, 
                "html"
            );
        });
        return false;
    });
    

    请注意,我没有使用 .live(),here's why,而是使用 .on()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 2011-04-19
      • 2011-05-21
      • 2013-05-08
      • 1970-01-01
      相关资源
      最近更新 更多