在Google自定义搜索(CSE)上添加“下一页”和“上一页”链接

时间:2013-02-04 19:58:45

标签: javascript search google-custom-search

是否可以在Google自定义搜索中添加指向页面结果的下一页和上一页链接?我找到了这个帖子How to show next/previous links in Google Custom Search Engine paging links,但代码适用于旧版Google自定义搜索。

新版本只会为您提供<gcse:searchresults-only></gcse:searchresults-only>这样的标记,并且所有内容都会从中生成。有任何想法吗?感谢

这是搜索结果的结果。

<script>
(function() {
    var cx = 'xxxxxx:xxxxx',
        gcse = document.createElement('script');

    gcse.type = 'text/javascript'; gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>

<gcse:searchresults-only></gcse:searchresults-only>

2 个答案:

答案 0 :(得分:0)

您可以使用searcher.cursor.currentPageIndex

中包含的searcher.gotoPage()google.setOnLoadCallback全部内容
window.customSearchControl = customSearchControl;

$(function() {

    var link = $('<a />', {
        'html' : 'link',
        'href' : '#',
        'class' : 'general-button',
        'style' : 'margin-right:1em'
    });

    var searcher = window.customSearchControl.getWebSearcher();

    var prev = link.clone().click(function(e) {
        e.preventDefault();
        var topage = searcher.cursor.currentPageIndex - 1;
        if(topage < 1) {
            topage = 0;
        }
        searcher.gotoPage(topage);
        return false;
    }).html('&lt; prev');

    var next = link.clone().click(function(e) {
        e.preventDefault();
        var topage = searcher.cursor.currentPageIndex + 1;
        if(topage > searcher.cursor.pages.length) {
            topage = 10;
        }
        searcher.gotoPage(topage);
        return false;
    }).html('next &gt;');

    $('#cse').append(prev).append(next);
});

答案 1 :(得分:0)

我使用了一些Jquery,但是可以不用。我在代码中加上了解释。

 //Listens for DOM changes
var observer = new MutationObserver(function (mutations, observer) {
    // fired when a mutation occurs
    makeNext();
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
    subtree: true,
    attributes: true
});

function makeNext() {
    //Make a Next element
    var el = $("<div></div>", {
        "id": "next",
        "class": "gsc-cursor-page", // need google class so is same look and works with them
        "text": "Next",
        "on": { // on click, find what is the current page, and trigger click on the one after
            "click": function () {
                $(".gsc-cursor-current-page").next(".gsc-cursor-page").click();
            }
        }
    });
    //When results load, lots of changes are made, but we only wont 1 Next button
    if ($("#next").length == 0) {
        $(".gsc-cursor").append(el);
    }
}