在点击事件中使用JQuery创建后查找所有Div

时间:2016-06-16 00:42:06

标签: javascript jquery html

我正在尝试查找从我的click事件创建的所有div并将它们分成另一个div(.wrapAll),数量为3.我在控制台时无法得到任何东西.log vars长度。我知道当我在静态输入的html上执行相同的过程时,这种方法很有效。以下是我的代码,谢谢你的想法!

jQuery(document).ready(function($) {
  // load default twitch channels
  $.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?', function(data) {
     //console.log(data);
  });
  // Bind 'Enter' to click event
  $(document).bind('keypress', function(e) {
    if (e.keyCode == 13) {
      $('#search').trigger('click');
    }
  });
  // manually search for games
  $('#search').on("click", function() {
    // clear previous results and get search term
    $('#results').html('');
    search = $('#searchTerm').val();
    // begin API call
    $.getJSON( "https://api.twitch.tv/kraken/search/streams?q=" + search + "", function(data2) {
      // console.log(data2.streams.length);
      data2.streams.forEach(function(entry) {
        //console.log(entry._links);
        var streamURL = entry.channel.url;   
        url = entry.preview.medium;
        $('#results').append('<div class="searchResults"><a href="' + streamURL + '" target="_blank"><img class="games" src=' + url + '/><p id="title"> Game: ' + entry.channel.game + '<br> Viewers: ' + entry.viewers +'<br> Is Mature: ' + entry.channel.mature + '<br> Status: ' + entry.channel.status + ' </p></a></div><hr>');
      });
    });
    // Get 3 divs and slice into one div to style ** problem child **
    var a = $('div[id^=searchResu]').find('div');
    console.log(a.length);
    for( var i = 0; i < a.length; i+=3 ) {
      a.slice(i, i+3).wrapAll('<div class="slide"></div>');
    }
  });
});

2 个答案:

答案 0 :(得分:0)

正如@charlietfl所说,您需要将包含div的代码放在getJSON的回调中。您的点击事件监听器将如下所示:

  $('#search').on("click", function() {
    // clear previous results and get search term
    $('#results').html('');
    search = $('#searchTerm').val();
    // begin API call
    $.getJSON( "https://api.twitch.tv/kraken/search/streams?q=" + search + "", function(data2) {
      // console.log(data2.streams.length);
      data2.streams.forEach(function(entry) {
        //console.log(entry._links);
        var streamURL = entry.channel.url;   
        url = entry.preview.medium;
        $('#results').append('<div class="searchResults"><a href="' + streamURL + '" target="_blank"><img class="games" src=' + url + '/><p id="title"> Game: ' + entry.channel.game + '<br> Viewers: ' + entry.viewers +'<br> Is Mature: ' + entry.channel.mature + '<br> Status: ' + entry.channel.status + ' </p></a></div><hr>');
      });
      // Get 3 divs and slice into one div to style ** problem child **
      var a = $('div[id^=searchResu]').find('div');
      console.log(a.length);
      for( var i = 0; i < a.length; i+=3 ) {
        a.slice(i, i+3).wrapAll('<div class="slide"></div>');
      }
    });
  });

答案 1 :(得分:0)

在这里查看此plunker。我相信这可以满足您的需求。

<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@2.1.4" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
    <script>
        jQuery(document).ready(function($) {
            function appendHtmlContent(resultHtmlContent) {
                resultHtmlContent = '<div class="slide">' + resultHtmlContent + '</div>';
                $('#results').append(resultHtmlContent);
            }

            function processSvcResponse(data2) {
                var count = 0,
                        searchResultContents = '',
                        $div = $("<div>", { class: "searchResults"});
                data2.streams.forEach(function(entry) {
                    var streamURL = entry.channel.url;
                    url = entry.preview.medium;

                    searchResultContents += '<div class="searchResults"><a href="' + streamURL 
                        + '" target="_blank"><img class="games" src=' + url + '/><p id="title"> Game: ' + entry.channel.game 
                        + '<br> Viewers: ' + entry.viewers + '<br> Is Mature: ' + entry.channel.mature 
                        + '<br> Status: ' + entry.channel.status + ' </p></a></div><hr>';

                    count++;

                    if(count === 3) {
                        appendHtmlContent(searchResultContents);
                        searchResultContents = '';
                        count =  0;
                    }
                });

                // more results that have not been appended?
                if(searchResultContents) {
                    appendHtmlContent(searchResultContents);
                }

            }

            // load default twitch channels
            $.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?', function(data) {});

            // Bind 'Enter' to click event
            $(document).bind('keypress', function(e) {
                if (e.keyCode == 13) {
                    $('#search').trigger('click');
                }
            });

            // manually search for games
            $('#search').on("click", function() {
                // clear previous results and get search term
                $('#results').html('');
                search = $('#searchTerm').val();
                // begin API call
                $.getJSON("https://api.twitch.tv/kraken/search/streams?q=" + search, processSvcResponse);

            });
        });
    </script>
  </head>

  <body>
    <input id="searchTerm" type="text" />
    <button id="search" type="button">Search</button>
    <div id="results"></div>
  </body>

</html>

如果我理解正确你想要迭代结果,并且每三个人将它包装在带有“滑块”类的div中。正如@charlietfl的评论中提到的,为了使用jQuery查询新创建的DOM元素,您必须在创建之后查询它们。在对jQuery.getJSON的调用中,第二个参数接受回调函数。签名是jQuery.getJSON(url,someCallbackFunction)。为了使你的代码更具可读性,我将“function(data2)”移动起来并将其命名为processSvcResponse。在processSvcResponse中,我从结果中构建一个HTML字符串,并使用计数器变量跟踪处理的结果数量。一旦计数器达到3,我将内容附加到结果div并重置计数器。这个解决方案不会像你原本打算那样“找到”div和slice / wrapAll,但是,我相信这仍然可以实现你的目标。