点击列表激活jquery Ajax并提取数字

Activate jquery Ajax on click on list and pull number

本文关键字:提取 数字 Ajax jquery 列表 激活      更新时间:2023-09-26

这是我从几个不同的在线信息构建的代码:

http://jsfiddle.net/spadez/qKyNL/6/

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 5000,
    beforeSend: function () {
        // Fadeout the existing content
        $('#content').fadeTo(500, 0.5);
    },
    success: function (data, textStatus) {
        // TO DO: Load in new content
        // Scroll to top
        $('html, body').animate({
            scrollTop: '0px'
        }, 300);
        // TO DO: Change URL
        // TO DO: Set number as active class
    },
    error: function (x, t, m) {
        if (t === "timeout") {
            alert("Request timeout");
        } else {
            alert('Request error');
        }
    },
    complete: function () {
        // Fade in content
        $('#content').fadeTo(500, 1);
    },
});

我的问题是,在使用e.prevent默认值时,如何通过点击其中一个分页列表链接(如1或2)触发ajax请求,使其可降解(如果禁用JavaScript,它仍然可以工作)。我想我试图在伪代码中做的是:

  1. 听一听是否点击了分页链接
  2. 抓取点击链接的编号(即点击了1或2次)

尝试

$('a').click(function(){
    var number = $(this).attr('href');//get the pg=1 value on the href
    alert(number);
    //ajax here
});

我不确定我是否完全理解你的问题,但这样的东西应该有效:

$(function() {
    var clicks = {};
    var sendAjax = function(href) {
        //do something with href
        $.ajax({
            url: "/ajax_json_echo/",
            type: "GET",
            dataType: "json",
            timeout: 5000,
            beforeSend: function () {
                // Fadeout the existing content
                $('#content').fadeTo(500, 0.5);
            },
            success: function (data, textStatus) {
                // TO DO: Load in new content
                // Scroll to top
                $('html, body').animate({
                    scrollTop: '0px'
                }, 300);
                // TO DO: Change URL
                // TO DO: Set number as active class
            },
            error: function (x, t, m) {
                if (t === "timeout") {
                    alert("Request timeout");
                } else {
                    alert('Request error');
                }
            },
            complete: function () {
                // Fade in content
                $('#content').fadeTo(500, 1);
            },
        });
    };
    $('a').click(function() {
        var href = $(this).attr('href');
        clicks[href] = clicks[href] ? clicks[href] + 1 : 1;
        sendAjax(href);
        return false; //disable the link
    });
});

你不能在链接1和链接2上设置一个onclick吗?

例如:

link1.click(function() {
  // do stuff with the ajax    
});