ДЕМО

Здравствуй,

Мне нужно сделать простой щелчок для динамически загружаемых данных из json для тега привязки. Я пробовал делать как с vanila js, так и с jquery, как я не смог этого добиться. не уверен, в чем проблема. та же функция запускается для обычного добавленного HTML

{{#pagination info.page.current_page info.page.per_page info.page.total_result_count}}
    <div id="pagination" class="pagination">{{#unless startFromFirstPage}}
        <a href="#">&lt;</a> {{/unless}} {{#each pages}} {{#if isCurrent}} [
        <a href="#">{{page}}</a> ] {{/if}} {{#unless isCurrent}}
        <a href="#">{{page}}</a> {{/unless}} {{/each}} {{#unless endAtLastPage}}
        <a href="#">&gt;</a> {{/unless}}
    </div>
    {{/pagination}}


var results = {};
var pageNum = 1;

$(document).ready(function () {
    getResult(1);
    document.getElementById('results').firstElementChild('.pagination').onclick = function () {
        var pageNum = $(this).text();
        getResult(pageNum);
        alert('hi ' + pageNum);
    }

    function getResult(pageNum) {
        $.getJSON('searchResult-' + pageNum + '.json', function (data) {
            var compileResult = Handlebars.compile($("#result").html());
            fullResult = compileResult(data);
            $("#results").html(fullResult);
        });
    }
});

Я не могу передавать данные в формате json ..

Так вот он ///

{
  "record_count": 5,
  "records": {
    "page": [
      {
        "body": "A Post in May This post is in the middle of the other ones, so we can show date range filtering with published_at.",
        "external_id": "c1173561bd0641bf0f5bd64c4d4d5a68939552c4",
        "sections": [
          "A Post in May"
        ],
        "title": "A Post in May",
        "updated_at": "2015-08-25T06:40:27Z",
        "image": "",
        "type": "post",
        "url": "http://crawler-demo-site.herokuapp.com/2012/05/01/a-post-in-may.html",
        "popularity": 1,
        "published_at": "2012-05-01T07:00:00Z",
        "info": "",
        "_index": "crawled",
        "_type": "page",
        "_score": 1,
        "_version": null,
        "_explanation": null,
        "sort": null,
        "highlight": {
          "title": "A <em>Post</em> in May",
          "sections": "A <em>Post</em> in May",
          "body": "A <em>Post</em> in May This post is in the middle of the other ones, so we can show date range filtering with published_at."
        },
        "id": "5025a3036052f6b650000008"
      },
      {
        "body": "First Post! Here is the first post on my site.",
        "external_id": "9508ace2e1ba669854eb49fbe9429952ff1a6d4c",
        "sections": [
          "First Post!"
        ],
        "title": "First Post!",
        "updated_at": "2015-08-25T06:40:27Z",
        "image": "",
        "type": "post",
        "url": "http://crawler-demo-site.herokuapp.com/2012/01/01/first-post.html",
        "popularity": 1,
        "published_at": "2012-01-01T08:00:00Z",
        "info": "",
        "_index": "crawled",
        "_type": "page",
        "_score": 1,
        "_version": null,
        "_explanation": null,
        "sort": null,
        "highlight": {
          "title": "First <em>Post</em>!",
          "sections": "First <em>Post</em>!",
          "body": "First <em>Post</em>! Here is the first post on my site."
        },
        "id": "5025a3036052f6b650000006"
      },
      {
        "body": "A post with an image This post has a photo. If you look at the metadata, it has an st:image meta tag. This meta tag displays the image as a thumbnail in search results.",
        "external_id": "92941161a37a99df8a74040c8a0061cfc266eeec",
        "sections": [
          "A post with an image"
        ],
        "title": "A post with an image",
        "updated_at": "2015-08-25T06:40:27Z",
        "image": "http://crawler-demo-site.herokuapp.com/images/cat.jpg",
        "type": "post",
        "url": "http://crawler-demo-site.herokuapp.com/2012/08/10/post-with-image.html",
        "popularity": 1,
        "published_at": "2012-08-10T07:00:00Z",
        "info": "",
        "_index": "crawled",
        "_type": "page",
        "_score": 3.8706326,
        "_version": null,
        "_explanation": null,
        "sort": null,
        "highlight": {
          "title": "A <em>post</em> with an image",
          "sections": "A <em>post</em> with an image",
          "body": "A <em>post</em> with an image This post has a photo. If you look at the metadata, it has an st:image meta tag. This meta tag displays the image as a thumbnail in search results."
        },
        "id": "5025a3036052f6b650000004"
      },
      {
        "body": "Swiftype Crawler Demo Site Welcome to the Swiftype Crawler Demo Site. Be sure to check out the source code to view the Swiftype meta tags that control how the crawler works. A post with an image A Post in May First Post! Learn more About this site.",
        "external_id": "3fccec2102880d859c1cf8f8b60609e62c7ab50b",
        "sections": [
          "Swiftype Crawler Demo Site"
        ],
        "title": "Swiftype Crawler Demo Site",
        "updated_at": "2015-08-25T06:39:41Z",
        "image": "",
        "type": "page",
        "url": "http://crawler-demo-site.herokuapp.com/",
        "popularity": 1,
        "published_at": "2017-06-28T06:39:54Z",
        "info": "",
        "_index": "crawled",
        "_type": "page",
        "_score": 0.009990831,
        "_version": null,
        "_explanation": null,
        "sort": null,
        "highlight": {
          "body": "Welcome to the Swiftype Crawler Demo Site. Be sure to check out the source code to view the Swiftype meta tags that control how the crawler works. A <em>post</em> with an image A Post in May First Post! Learn more About this site."
        },
        "id": "5025a3036052f6b650000002"
      },
      {
        "body": "About This Site This site is used for demonstrating the Swiftype Crawler. As you can see from the source code of this page, it has a st:type meta tag with a value of page as opposed to post. This allows filtering of blog posts from regular pages.",
        "external_id": "261733cee3ca9c280320efc0d79ad8566ddbb9a9",
        "sections": [
          "About This Site"
        ],
        "title": "About This Site",
        "updated_at": "2015-08-25T06:40:27Z",
        "image": "",
        "type": "page",
        "url": "http://crawler-demo-site.herokuapp.com/about.html",
        "popularity": 1,
        "published_at": "2017-06-28T06:40:31Z",
        "info": "",
        "_index": "crawled",
        "_type": "page",
        "_score": 0.0057682088,
        "_version": null,
        "_explanation": null,
        "sort": null,
        "highlight": {
          "body": "for demonstrating the Swiftype Crawler. As you can see from the source code of this page, it has a st:type meta tag with a value of page as opposed to <em>post</em>. This allows filtering of blog posts from regular pages."
        },
        "id": "5025a3046052f6b65000000a"
      }
    ]
  },
  "info": {
    "page": {
      "query": "post",
      "current_page": 1,
      "num_pages": 1,
      "per_page": 20,
      "total_result_count": 5,
      "facets": {}
    }
  },
  "errors": {}
}
0
Developer 29 Июн 2017 в 15:00
getJSON - асинхронный процесс, поэтому в вашем коде происходит то, что вы добавляете прослушиватель событий к несуществующему элементу. Чтобы исправить это, поместите логику добавления прослушивателя событий в функцию обратного вызова success getJSON.
 – 
Fahmi
29 Июн 2017 в 20:02

1 ответ

Лучший ответ

Только для других разработчиков, если возникла такая же проблема, я исправил ее, добавив документ, а затем привязав событие щелчка.

Var results = {}; var pageNum = 1;

$(document).ready(function () {
    getResult(1);
    $(document).on('click', '.pagination a', function () {
        //alert('hi ' + pageNum);
        var pageNum = $(this).text();
        getResult(pageNum);  
    });

    function getResult(pageNum) {
        $.getJSON('searchResult-' + pageNum + '.json', function (data) {
            var compileResult = Handlebars.compile($("#result").html());
            fullResult = compileResult(data);
            $("#results").html(fullResult);
        });
    }
});
0
Developer 30 Июн 2017 в 07:09